双精度的精确二进制表示形式

Exact binary representation of a double

本文关键字:表示 二进制 双精度      更新时间:2023-10-16

可能的重复项:
在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 );
}