如何在计算机内存中打印 long double 的二进制表示形式?

How to print binary representation of a long double as in computer memory?

出于某些原因,我必须打印 long double 数字的二进制表示形式。我想查看保留在计算机内存中的确切格式。

我回答了以下问题,其中 union 是解决方案。对于 float,替代数据类型是 unsigned int,因为两者都是 32 位的。对于 double,它是 unsigned long int,因为它们都是 64 位的。但在long double中,96-bit/128-bit(取决于平台)没有类似的等效内存消费者。那么,解决方案是什么?

访问过的问题:

  1. Print binary representation of a float number in C++
  2. Binary representation of a double
  3. Exact binary representation of a double
  4. How do I display the binary representation of a float or double?

注意:

它被标记为问题的重复 How to print (using cout) the way a number is stored in memory? !

真的吗?提到的问题是关于整数的,接受的解决方案是 bitset ,它只是截断了浮点数部分。我的主要观点是浮点表示,与该题内容无关

一如既往,别名任意内存的方法是使用 unsigned chars 的数组。时期。所有这些 "union" 解决方案都具有未定义的行为,因此实际上根本不是 "solutions"。

所以复制到一个unsigned char数组中,然后一个一个地打印出字节值。

顺便说一下,long double 不一定是 96 位。这将取决于平台。

#include <iostream>
#include <algorithm>

int main()
{
    const long double x = 42;
    unsigned char     a[sizeof(long double)];

    std::copy(
        reinterpret_cast<const unsigned char*>(&x),
        reinterpret_cast<const unsigned char*>(&x) + sizeof(long double),
        &a[0]
    );

    std::cout << "Bytes: " << sizeof(long double) << "\nValues: ";
    std::cout << std::hex << std::showbase;
    for (auto el : a) {
        std::cout << +el << ' ';
    }

    std::cout << '\n';
}

(live demo)