Salim Saloumi
Salim Saloumi

Reputation: 21

convert 4 bytes to float matlab

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.

Upvotes: 2

Views: 9689

Answers (2)

Ilya Kobelevskiy
Ilya Kobelevskiy

Reputation: 5345

To avoid reinventing the wheel, simply use

A = fread(obj,size,'precision')

as described in documentation

For example,

[A,count] = fread(obj, 18, 'float32');

should read 18 4 byte floats.

Upvotes: 5

Hoki
Hoki

Reputation: 11812

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.

Upvotes: 5

Related Questions