如何打印长双的二进制表示在计算机内存中? [英] How to print binary representation of a long double as in computer memory?
问题描述
由于某些原因,我必须打印 long double
数字的二进制表示。
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.
我经历了以下问题,其中以联合
是解决方案。对于 float
,备用数据类型为 unsigned int
,因为两者都是32位。对于 double
,它们都是64位的 unsigned long int
。但在 long double
中,它是96位/ 128位(取决于平台),它没有类似的等效内存消耗。那么,解决方案是什么?
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?
- 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?
注意:
它被标记为问题的重复 C ++ - 如何打印(使用cout)数字存储在内存中的方式?
它?问题提到的问题谈到整数和接受的解决方案是 bitset
这只是截断浮点部分。我的主要观点是与该问题的内容无关的浮点表示。
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.
推荐答案
方式到任意内存的别名是一个 unsigned char
的数组。期。所有这些联合解决方案都有未定义的行为,因此实际上不是解决方案。
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.
因此,复制到 unsigned char $
So copy into an unsigned char
array, then just print out the byte values one by one.
顺便说一下, long double
是不一定是96位。这将取决于平台。
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';
}
这篇关于如何打印长双的二进制表示在计算机内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!