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

陌路散爱 提交于 2019-12-08 13:59:53

问题


I have to print the binary representation of a long double number for some reasons. I want to see the exact format as it remains in the computer memory.

I went through the following questions where taking a union was the the solution. For float, alternate datatype was unsigned int as both are 32-bit. For double, it was unsigned long int as both are 64-bit. But in of long double, it is 96-bit/128-bit (depending on platform) which has no similar equivalent memory consumer. So, what would be the solution?

Visited Questions:

  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?

ATTENTION:

It is marked as duplicate of the question How to print (using cout) the way a number is stored in memory? !

Really is it? The question mentioned question talked about integer number and accepted solution of it was bitset which just truncates the floating-point part. My main point of view is floating-point representation which has no relation with the content of that question.


回答1:


As always, the way to alias arbitrary memory is with an array of unsigned chars. Period. All those "union" solutions have undefined behaviour and are thus in fact not "solutions" whatsoever.

So copy into an unsigned char array, then just print out the byte values one by one.

Incidentally, long double is not necessarily 96-bit. It'll depend on the platform.

#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)



来源:https://stackoverflow.com/questions/37861410/how-to-print-binary-representation-of-a-long-double-as-in-computer-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!