Exact binary representation of a double [duplicate]

大兔子大兔子 提交于 2019-12-01 05:33:47
union myUnion {
    double dValue;
    uint64_t iValue;
};

myUnion myValue;
myValue.dValue=123.456;
cout << myValue.iValue;

Update:

The version above will work for most purposes, but it assumes 64 bit doubles. This version makes no assumptions and generates a binary representation:

    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";
    }

This way is guaranteed to work by the standard:

double d = -0.0;
uint64_t u;
memcpy(&u, &d, sizeof(d));
std::cout << std::hex << u;

Try:

printf("0x%08x\n", myFloat);

This should work for a 32 bit variable, to display it in hex. I've never tried using this technique to see a 64 bit variable, but I think it's:

printf("%016llx\n", myDouble);

EDIT: tested the 64-bit version and it definitely works on Win32 (I seem to recall the need for uppercase LL on GCC.. maybe)

EDIT2: if you really want binary, you are best off using one of the other answers to get a uint64_t version of your double, and then looping:

for ( int i = 63; i >= 0; i-- )
{
    printf( "%d", (myUint64 >> i ) & 1 );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!