I read from the serial port 4 bytes and I want to create a Matlab function to convert them into a float number for example: if I read A=[65 240 0 0] I must have 30 according to IEEE754 standard. - I have used Simulink block "byte unpack" but i have problems. in fact I should read over 18 parameters. each parameters is 4 bytes array.then I should use 18 byte unpack.
By default, Matlab will use double precision to store any new value which doesn't have a type specified. If you know you are reading byte, then the best is to collect them directly as uint8 (the unsigned byte type of Matlab) if you can (in your call to fread or equivalent).
If you cannot collect them directly as uint8 then cast them as such then use the typecast function.
A = [65 240 0 0] ; %// Collected bytes
A = uint8(A) ; %// cast them to "uint8" if they are not already
Afloat = typecast( A , 'single') ; %// cast the 4 bytes as a 32 bit float
wait a minute:
Afloat =
8.6186862e-41
oops, it seems the byte ordering used by your collection mechanism is the opposite as the one used by Matlab. No problem, you can just change the endianness by "flipping" the byte array.
So instead, use:
>> Afloat = typecast( fliplr(A) , 'single')
Afloat =
30
success :)
You can also look at the function swapbytes to manage the endianess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With