简体   繁体   English

浮点二进制表示中的混淆

[英]confusion in floating-point binary representation

I have tried to output following but got confused, 我尝试输出以下内容,但感到困惑,

    float f=3.4;
    char *cp;
    cp=(char *)&f;
    printf("%d\n",*cp);

normalized number I have calculated IEEE 754 std is, 我计算过的IEEE 754 std的归一化数字是

0 10000000 10110011001100110011001

that's why I assumed at cp now value has, 这就是为什么我现在假设cp值具有的原因,

10011001

after convert to 2's complement, 转换为2的补码后,

01100111

It should output -103 , but I got -102 in my bloodshed/DevC. 它应该输出-103,但是我在流血/ DevC中得到了-102。 why such output??? 为什么这样的输出???

That's because f is being rounded up: 这是因为f被四舍五入:

3.4 = 10110011001100110011001 100110011001...  (repeating 1001)

rounds up to: 舍入为:

3.4 = 10110011001100110011010
                            ^

when stored into single-precision floating-point. 当存储到单精度浮点中时。

Now when you extract out the last 8 bits, you're actually getting 10011010 instead of 10011001 . 现在,当您提取出最后8位时,您实际上得到的是10011010而不是10011001

Converting 10011010 -> -102 instead of -103 . 转换10011010 > -102而不是-103

I think you miscalculated: 我认为您算错了:

Prelude> decodeFloat (3.4 :: Float)
(14260634,-22)
(0.03 secs, 2929112 bytes)
Prelude> Numeric.showHex (fst it) ""
"d9999a"

The mantissa ends in 1010 . 尾数在1010结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM