How do I convert a byte representation of a number into its decimal equivalent and viceversa in Matlab/Octave?
February 21, 2012 in Matlab, Octave, Recipes
Let’s consider the case of a standard single precision number (a float) that is represented by 4 bytes. Suppose we want to find the byte hexadecimal representation of x=3.141592. To accomplish this we can use the function typecast:
> xBytes = typecast(single(x), 'uint32'); > xBytesHex = dec2hex(xBytes) xBytesHex = 40490FD8
Note that the second step is superflous if we just want to print the number representation. In this case we could just change the output format:
> format hex; > xBytes > xBytes = 40490fd8
To go from the hexadecimal binary representation to the decimal single precision representation we just invert the steps:
> xBytes = uint32(hex2dec('40490fd8'));
> x = typecast(xBytes, 'single')
x = 3.1416
Note that if you were interested in a double precision number (8 bytes) you would just have to substitute uint32 with uint64 and single with double. Finally if you need to convert between different type of endianness you can use the function swapbytes on the byte representation of the number.

thanks for share!