c++ - 理解 float 的二进制表示

标签 c++ floating-point binary

我使用以下代码打印 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

有人可以解释一下输出二进制数的哪些部分对应于 float 的哪些部分吗?我希望第一个是 10000...。第二个有道理。我对之后的每一个输出都很困惑,尤其是最后一个。

提前致谢。

最佳答案

假设您指的是 IEEE754 二进制浮点格式,则 32 位浮点由 1 个符号位、8 个指数位和 23 个有效数(也称为小数)位组成。以下是您的示例之一 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)

您可以在维基百科页面上阅读有关格式本身的更多信息:https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats以及单精度格式的细节:https://en.wikipedia.org/wiki/Single-precision_floating-point_format

关于c++ - 理解 float 的二进制表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480843/

相关文章:

C++ 将 lexical_cast double boost 为字符串

c++ - 如何从 C++ 代码打开一个新终端并在其中写入

c++ - array[0] = 0 这怎么可能?

math - float 学有问题吗?

c# - 为什么某些 float 在 C# 中可以准确表示?

c# - 如何使用 C# 计算整数的二进制表示中的尾随零

php - Laravel 在使用 HTTPS 时添加/删除字符

c++ - 检查是否在 std::ostream 中序列化了某些内容

c - 在系统之间传输二进制文件

c - 为什么两次计算给出不同的答案?