简体   繁体   English

MATLAB中的单精度浮点到字节数组

[英]Single-precision float to byte array in MATLAB

Say I have the following single-precision floating point number in Matlab 假设我在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 我想将其表示为遵循IEEE 754的4个字节的数组。正确的表示应为

b = [123, 20, 22, 192]

Currently, I am using fread and fwrite to do the conversion, as in 目前,我正在使用freadfwrite进行转换,如

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. 有关将字节数组转换为浮点数的文章(例如here ),但是我不确定如何朝相反的方向前进。 Any suggestions? 有什么建议么?

You can use the typecast function to cast between datatypes without changing the underlying data, ie reinterpret data using another type. 您可以使用typecast函数在数据类型之间进行转换,而无需更改基础数据,即使用另一种类型重新解释数据。 In your case, you will want to cast from single to uint8 (byte) datatype. 在您的情况下,您将需要从single类型转换为uint8 (字节)数据类型。 This is done by 这是通过

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

as required. 按要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM