【问题标题】:Integer representation as float, clarification needed整数表示为浮点数,需要澄清
【发布时间】:2012-04-29 09:27:09
【问题描述】:

拿走

int x = 5;
float y = x;

//"I know it's a float .. you know it's a float .. but take it's address
// and pretend you're looking at an integer and then dereference it"

printf("%d\n", *(int*)&y); //1084227584

为什么我会看到这个数字?

  • 5 在二进制是0101
  • 5 可以认为是(1.25 * 2^2),也就是说

可以表示为:

[sign bit]                              - 0
[8 bits worth of exp] - 129 (129-127=2) - 1000|0001
[23 bits of .xxxxxxx] - 25              - 1100|1

放在一起,我有

[sign bit][8 bits worth of exp][23 bits worth of .xxx]
0         10000001             11001000000000 //2126336

请问我错过了什么?

【问题讨论】:

  • 浮点表示会因您的架构和环境而异。这段代码的运行环境是什么?
  • hmm .. 在 64 位 mac 上运行

标签: c floating-point number-formatting


【解决方案1】:

为什么我会看到这个数字?因为您将浮点数打印为 int。

我知道,我知道,您显然已经知道这一点,但最重要的是行为未定义。在您的系统上,整数和浮点数是否相同?您是否查看过编译器用于存储浮点数的标准?

【讨论】:

  • 嗯,这个想法是看看转换为 int* 如何改变编译器理解位的方式。我当然期望一个不同的(大)数字,只是想了解为什么我看到我所看到的
【解决方案2】:

其他人指出它不可移植......但您已经知道这一点,并且您指定了 64 位 OS X。基本上,您的尾数错误。 1.251.0 的隐式前导位表示。尾数的第一个显式位表示0.5,第二个位表示0.25。所以尾数其实是:01000000000000000000000.

符号位0,偏置指数10000001,后跟尾数给出: 0x40a000001084227584 十进制。

【讨论】:

  • @JAM ?我已经提供了符号、指数和尾数位模式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 2011-11-09
  • 2012-07-18
  • 1970-01-01
相关资源
最近更新 更多