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?
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.
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