I want to reinterpret 4 bytes as IEEE 754 single-precision binary in C.
To obtain the bytes that represent float
, I used:
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:
Buff = *(float*)&aux;
In that second case nothing apears on "Buff"
float
. What am I doing wrong in the second case?
2 problems:
Buff = *(float*)&aux;
attempts to use the address of an array of 4 int
as a pointer to a float. aux[]
is perhaps 16 bytes long and a IEEE 754 single-precision binary float
is expected to be 4 bytes.
Both casts: (uint32_t*)
and (float*)
invoke undefined behavior as well as alignment and anti-aliasing issues. Better to use a 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.