双精度的精确二进制表示形式
Exact binary representation of a double
我可能的重复项:
在C++中浮点为二进制
有一个非常小的双变量,当我打印它时,我得到 -0。(使用 C++(。现在为了获得更好的精度,我尝试使用
cout.precision(18); \i think 18 is the max precision i can get.
cout.setf(ios::fixed,ios::floatfield);
cout<<var;\var is a double.
但它只写 -0.00000000000...
我想看看变量的确切二进制表示。
换句话说,我想看看这个变量的堆栈内存/寄存器中写入了什么二进制数。
union myUnion {
double dValue;
uint64_t iValue;
};
myUnion myValue;
myValue.dValue=123.456;
cout << myValue.iValue;
更新:
上面的版本适用于大多数目的,但它假设 64 位双精度。 此版本不做任何假设,并生成二进制表示形式:
double someDouble=123.456;
unsigned char rawBytes[sizeof(double)];
memcpy(rawBytes,&someDouble,sizeof(double));
//The C++ standard does not guarantee 8-bit bytes
unsigned char startMask=1;
while (0!=static_cast<unsigned char>(startMask<<1)) {
startMask<<=1;
}
bool hasLeadBit=false; //set this to true if you want to see leading zeros
size_t byteIndex;
for (byteIndex=0;byteIndex<sizeof(double);++byteIndex) {
unsigned char bitMask=startMask;
while (0!=bitMask) {
if (0!=(bitMask&rawBytes[byteIndex])) {
std::cout<<"1";
hasLeadBit=true;
} else if (hasLeadBit) {
std::cout<<"0";
}
bitMask>>=1;
}
}
if (!hasLeadBit) {
std::cout<<"0";
}
这种方式保证按标准工作:
double d = -0.0;
uint64_t u;
memcpy(&u, &d, sizeof(d));
std::cout << std::hex << u;
尝试:
printf("0x%08xn", myFloat);
这应该适用于 32 位变量,以十六进制显示它。我从未尝试过使用这种技术来查看 64 位变量,但我认为它是:
printf("%016llxn", myDouble);
编辑:测试了64位版本,它绝对适用于Win32(我似乎记得在GCC上需要大写LL..也许(
EDIT2:如果你真的想要二进制,你最好使用其他答案之一来获得你的替身的uint64_t版本,然后循环:
for ( int i = 63; i >= 0; i-- )
{
printf( "%d", (myUint64 >> i ) & 1 );
}
相关文章:
- 浮点数为 32 位和 64 位二进制表示形式
- 如何将uint8_t的二进制表示形式读取为数字
- 二进制表示,如何获得"相关位"?
- C++ 如何以二进制格式表示字符串?
- 编译器C++如何在二进制代码中表示整数
- 了解浮点数的二进制表示形式
- 如何在 mfc c++ 中流式传输.zip文件夹的二进制表示形式
- 浮点逆二进制表示
- 以C++显示浮点类型的二进制表示形式
- 如何使用C 将二进制数字的字符串转换为其签名的十进制表示
- 在二进制表示中将二进制 std::string 转换为 int
- 如何在没有循环的二进制数字表示中只计算1位
- 如何在计算机内存中打印长双重表示的二进制表示
- 将uint8_t转换为其二进制表示
- 如何在C++中操作和表示二进制数
- 如何在C++中表示二进制字节数组数据
- 如何在编程语言中表示二进制字段
- 如何在C++中表示二进制数(用于霍夫曼编码器)
- 如何在表示二进制文件的字符串中查找整数
- 将表示二进制的字符串转换为表示等效十六进制的字符串