如何通过在 C 中转换为 char * 来访问 float 的字节表示?

问题描述 投票:0回答:1

我正在学习 C,部分是为了习惯指针,部分是为了了解 IEEE 754 浮点数,我尝试了以下方法:

#include <stdio.h>

int main() {

    float f1 = -12.78;
    const char *p =  (char *)&f1;
    for(int i=0; i < sizeof(f1); i++) {
        printf("i: %i and p: %p and byte is %#x\n",i,p,*p);
        p++;
    }
}

我没有收到任何警告或错误(与我之前尝试过的大多数版本不同!),但我确实得到了奇怪的结果:

i: 0 and p: 0x16ce13368 and byte is 0xffffffe1
i: 1 and p: 0x16ce13369 and byte is 0x7a
i: 2 and p: 0x16ce1336a and byte is 0x4c
i: 3 and p: 0x16ce1336b and byte is 0xffffffc1

我对 IEEE 754 的(有限)理解是 -12.78 确实是

e1 7a 4c c1
(以字节为单位),但为什么第一个字节显示为
ff ff ff e1
(最后一个字节也类似)?

有更好的方法吗?

我也尝试过使用字符数组,但并没有走得太远。我还尝试使用 void *p 来访问保存浮点的内存,但也无法使其工作。

c casting
1个回答
0
投票

对于这种类型的位级访问,建议使用

union

// Assumes float == IEEE 754 single precision
typedef union 
{
    uint32_t bits;
    float value;
} FLOATBITS, *PFLOATBITS;

现在,如果您填充

FLOATBITS::value
,您可以通过变量
bits
访问其位表示,因为它与
value
占用相同的内存。

© www.soinside.com 2019 - 2024. All rights reserved.