我正在尝试编写一个自动化测试程序,它要求我生成一个 int 数组数据流(实际上保存 float 据)
为了生成该 int 数组,我尝试
将 float 写入char字节数组,然后
将 char 字节数组转换为 int 数组,稍后
将数字从 int 数组转换回 float (不丢失小数点)。
我能够毫无问题地执行步骤 1 和 2,但无法使用 (float)(*int_ptr) 将 int 数组转换回浮点型。
我的代码:
int ibuff[10];
int *int_ptr;
float f=0.1;
char c [sizeof(float)];
memcpy(c, &f, sizeof(float)); //now c is 0x3f800000;
ibuff[0]=(c[3]<<24 | c[2]<<16 | c[1]<<8 | c[0]); //ibuff[0] is now also 0x3f800000
int_ptr=&ibuff[0];
printf("%f\n", (float)(*int_ptr)); //this will print out 1065353216.0000, and not 1.0 as I expected
最佳答案
您的直接问题来自于将取消引用的整数指针 int_ptr
转换为 float
,然后尝试将该值打印为 float
。您当前正在尝试:
printf("%f\n", (float)(*int_ptr));
正如您所发现的那样,这是行不通的。您想要做的是将 int_ptr
保存的地址处的值解释为 float
。为了实现这一点,您将需要:
printf("%f\n", *(float*)(int_ptr));
虽然您可以按照自己喜欢的方式查看地址,但您必须确保不违反 C 标准规则 6.5 中规定的严格别名规则( 6)
和 6.5 (7)
。指定了有限的异常(exception)情况,但如上所述:“目的......是指定对象可能会或可能不会别名的情况。”从技术上讲,您的转换来自 int
到 float
是一种违规行为,它被指针的使用所掩盖(通过插入字符数组的使用来实现,这使情况变得更加困惑)。
关于c - 如何将 int 数组(保存十六进制浮点值)转换回 C 中的浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36298817/