繁体   English   中英

了解浮点数的二进制表示形式

[英]Understanding the binary representation of a float

我正在使用以下代码来打印浮点数的“二进制表示形式”:

template<class F>
void printBinary(F value)
{
    std::cout <<
        std::bitset<sizeof(F) * 8>(*reinterpret_cast<unsigned long*>(&value)).to_string()
    << std::endl;
}

int main()
{
    float f = 1;
    printBinary(f);
    f = 2;
    printBinary(f);
    f = 3;
    printBinary(f);
    f = 4;
    printBinary(f);
    f = 16;
    printBinary(f);
    f = 0.2;
    printBinary(f);
}

它输出:

00111111100000000000000000000000
01000000000000000000000000000000
01000000010000000000000000000000
01000000100000000000000000000000
01000001100000000000000000000000
00111110010011001100110011001101

有人可以解释输出二进制数字的哪些部分对应于浮点数的哪些部分? 我希望第一个是10000... 第二点很有意义。 我对之后的每个输出都感到困惑,尤其是最后一个输出。

提前致谢。

假设您使用的是IEEE754二进制浮点格式,则32位浮点数由1个符号位,8个指数位和23个有效(aka分数)位组成。 这是示例0.2表示方式,例如:

                  3  2          1         0
                  1 09876543 21098765432109876543210
                  S ---E8--- ----------F23----------
          Binary: 0 01111100 10011001100110011001101
             Hex: 3E4C CCCD
       Precision: SP
            Sign: Positive
        Exponent: -3 (Stored: 124, Bias: 127)
       Hex-float: +0x1.99999ap-3
           Value: +0.2 (NORMAL)

您可以在Wikipedia页面上了解有关格式本身的更多信息: https : //en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats以及单精度格式的详细信息, 网址为: https : //en.wikipedia.org/维基/单precision_floating-point_format

暂无
暂无

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

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