Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single-precision float to byte array in MATLAB

Say I have the following single-precision floating point number in Matlab

a = single(-2.345)

I would like to represent the number as an array of 4 bytes, following IEEE 754. The correct representation should be

b = [123, 20, 22, 192]

Currently, I am using fread and fwrite to do the conversion, as in

fid = fopen('test.dat','wb')
fwrite(fid,a,'float')
fclose(fid)

fid = fopen('test.dat','rb');
b = fread(fid)'

which well enough, but I suspect there is a much easier and faster way to do the conversion without reading/writing from a file.

There have been a few posts about converting a byte array to a float (such as here), but I'm unsure how to proceed to go in the opposite direction. Any suggestions?

like image 738
adammgannon Avatar asked May 08 '26 20:05

adammgannon


1 Answers

You can use the typecast function to cast between datatypes without changing the underlying data, i.e. reinterpret data using another type. In your case, you will want to cast from single to uint8 (byte) datatype. This is done by

a = single(-2.345);
typecast(a,'uint8')
ans =
  123   20   22  192

as required.

like image 108
hbaderts Avatar answered May 11 '26 01:05

hbaderts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!