Search code examples
matlabfloating-pointoctaveendianness

Octave/matlab: uint8 array to float


I'm receiving Big-endian data from a socket (using the socket package) in Octave.

Some parts of this data contain float (32bit) values, but these are encoded as uint8's.

For example: (67 128 0 0)

Is there a way in Octave to calculate the corresponding float/single value?


Solution

  • The way to do it is using typecast():

    octave> typecast (uint8 ([67 128 0 0]), "single")
    ans =    4.6012e-41
    

    If you have an endianess issue, use swapbytes():

    octave> swapbytes (typecast (uint8 ([67 128 0 0]), "single"))
    ans =  256
    

    If you want to play more with it, or require more flexibility, take also a look at bitpack() and bitunpack():

    octave> data = uint8 ([67  128    0    0   67  127    0    0   67  126    0    0   67  125    0    0])
    data =
    
       67  128    0    0   67  127    0    0   67  126    0    0   67  125    0    0
    
    octave> bitpack (bitunpack (flipud (reshape (data, 4, []))), "single")
    ans =
    
       256
       255
       254
       253