how to combine 8-bit binary to form a 16-bit binary

11 Ansichten (letzte 30 Tage)
Earl Gozum
Earl Gozum am 12 Aug. 2021
Beantwortet: Steven Lord am 13 Aug. 2021
The code so far is below, the inputs are two ip address, ip1 = '192.168.0.31', ip2 = '192.168.0.30', upd = 10
the task is to do a ipv4 upd pseudo header checksum, with the input values in decimal and output in binary number
the basic idea as an example:
given an ip address = '192.168.30.'
192 = 1100 0000
168 = 1010 1000
0 = 0000 0000
31 = 0001 1111
the two 8-bit binary should be combined to form a 16-bit value:
192 and 168 = 1100 0000 1010 1000
0 and 31 = 0000 0000 0001 1111
function [hd] = in(ip1,ip2,udp) % input values in decimals
source = str2double(strplit(ip1, '.'));
dest = str2double(strplit(ip2, '.'));
protocol = 17; % udp protocol set to 17
hd1 = de2bi((source),8 , 'left-msb'); % converting from decimal to binary
hd2 = de2bi((dest),8, 'left-msb');
end

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 12 Aug. 2021
de2bi(source(1:2:end)*256 + source(2:2:end), 16, 'left-msb')

Weitere Antworten (1)

Steven Lord
Steven Lord am 13 Aug. 2021
Take a look at the typecast and swapbytes functions.
format hex
x = uint8([192 168])
x = 1×2
c0 a8
y = typecast(x, 'uint16')
y = uint16
a8c0
z = swapbytes(y)
z = uint16
c0a8
format longg
results = [uint16(x); y 0; z 0]
results = 3×2
192 168 43200 0 49320 0

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by