可能的重复:
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...
我想查看 var 的精确二进制表示。
换句话说,我想看看这个变量的堆栈内存/寄存器中写入了什么二进制数。
union myUnion {
double dValue;
uint64_t iValue;
};
myUnion myValue;
myValue.dValue=123.456;
cout << myValue.iValue;
Update:
上面的版本适用于大多数用途,但它假定 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";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)