How to separate first 8 digits in binary format and convert them to the hex?

6 visualizaciones (últimos 30 días)
I need a code to ask me to enter a number in binary format, and then separate them byte by byte (each 8 digits) then displace low and high value bytes and convert them to the hex.
for example if the input is 1000000011000000 then the output would be c080

Respuesta aceptada

dpb
dpb el 7 de Jul. de 2013
Editada: dpb el 7 de Jul. de 2013
Enter the value as a string and then convert. First below does the endian swap directly; if want to do this way write a little helper function that does it.
Alternatively, use the builtin swapbytes function on the internal representation.
MATL
>> b='1000000011000000'
b =
1000000011000000
>> dec2hex(bin2dec([b(9:16) b(1:8)]))
ans =
C080
>> dec2hex(swapbytes(uint16(bin2dec(b))))
ans =
C080
>>

Más respuestas (2)

Image Analyst
Image Analyst el 7 de Jul. de 2013
Editada: Image Analyst el 7 de Jul. de 2013
Try this:
binaryString = '1000000011000000'
decimalNumber = bin2dec(binaryString)
hexString = dec2hex(decimalNumber)
Adapt as necessary. To get substrings
ss = s(1:8) % Get first 8 digits.
To reverse digits:
sr = s(end: -1 : 1)

Jan
Jan el 7 de Jul. de 2013
Editada: Jan el 7 de Jul. de 2013
bin2dec and dec2hex have a certain overhead, which can be avoided:
str = '1000000011000000';
bin = reshape(str - '0', 8, [])';
d = bin * pow2(:-1:0)';
d = d([2,1]); % Swap bytes
h = sprintf('%x', d);

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by