问题
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:
- Print binary representation of a float number in C++
- Binary representation of a double
- Exact binary representation of a double
- 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 char
s. 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