我正在学习C,部分是为了习惯指针,部分是为了了解IEEE 754浮动,我try 了以下操作:
#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++;
}
}
我没有收到任何警告或错误(与我之前try 过的大多数版本不同!),但我确实得到了奇怪的结果:
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
(最后一个字节也是如此)?
有更好的方法吗?
我还try 使用char数组,但没有取得太大进展.我还try 使用val *p来访问保存float的内存,但也无法让它发挥作用.