[英]Reinterpret bytes as float in C (IEEE 754 single-precision binary)
I want to reinterpret 4 bytes as IEEE 754 single-precision binary in C. 我想将4个字节重新解释为C中的IEEE 754单精度二进制。
To obtain the bytes that represent float
, I used: 为了获得表示
float
的字节,我使用了:
num = *(uint32_t*)&MyFloatNumber;
aux[0] = num & 0xFF;
aux[1] = (num >> 8) & 0xFF;
aux[2] = (num >> 16) & 0xFF;
aux[3] = (num >> 24) & 0xFF;
To reinterpret the bytes as a float
, I'm trying: 要将字节重新解释为
float
,我正在尝试:
Buff = *(float*)&aux;
In that second case nothing apears on "Buff" 在第二种情况下,“ Buff”没有任何反应
float
. float
。 What am I doing wrong in the second case? 在第二种情况下我怎么了?
2 problems: 2个问题:
Buff = *(float*)&aux;
attempts to use the address of an array of 4 int
as a pointer to a float. 尝试将4
int
数组的地址用作指向浮点数的指针。 aux[]
is perhaps 16 bytes long and a IEEE 754 single-precision binary float
is expected to be 4 bytes. aux[]
长度可能为16个字节,并且IEEE 754单精度二进制 float
预计为4个字节。
Both casts: (uint32_t*)
and (float*)
invoke undefined behavior as well as alignment and anti-aliasing issues. (uint32_t*)
和(float*)
调用未定义的行为以及对齐和抗锯齿问题。 Better to use a union
. 最好使用
union
。
int main(void) { union { float f; unsigned char uc[sizeof(float)]; } x; // float to bytes xf = 1.23f; printf("%x %x %x %x\\n", x.uc[0], x.uc[1], x.uc[2], x.uc[3]); // bytes to float x.uc[0] = 0xA4; x.uc[1] = 0x70; x.uc[2] = 0x9D; x.uc[3] = 0x3F; printf("%.8e\\n", xf); }
Output 输出量
a4 70 9d 3f
1.23000002e+00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.