将浮点变量显示为十六进制整数会拧紧相邻整数

时间:2012-05-03 18:01:58

标签: c floating-point hex printf format-specifiers

我有这个简单的程序

#include <stdio.h>
int main(void)
{
 unsigned int a = 0x120;
 float b = 1.2;
 printf("%X %X\n", b, a);
 return 0;
}

我预计输出为

some-value 120  (some-value will depend on the bit pattern of `float b` )

但我明白了

40000000 3FF33333

为什么a的价值被搞砸了? %X将其参数视为signed int,因此它应该从堆栈中检索4个字节并打印b的calue,然后获取接下来的4个字节打印{{1}的值} a

2 个答案:

答案 0 :(得分:8)

首先,将参数传递给printf与格式说明符不匹配是未定义的行为。

其次,float在传递给double时会升级为printf,因此它是8个字节而不是4个字节。哪个字节被解释为unsigned格式所期望的两个printf值取决于推送参数的顺序。

答案 1 :(得分:2)

如果要查看存储的float的位,请使用union:

 float b = 1.2;
 union {
      float  f;
      int    i;
 } u;
 u.f = b;

 printf ("%x\n", u.i);

结果(32位x86):

3f99999a