5

可能重复:
在 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 的确切二进制表示。

换句话说,我想看看这个变量的堆栈内存/寄存器中写入了什么二进制数。

4

3 回答 3

7
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";
    }
于 2011-12-15T14:33:05.533 回答
5

这种方式保证按标准工作:

double d = -0.0;
uint64_t u;
memcpy(&u, &d, sizeof(d));
std::cout << std::hex << u;
于 2011-12-15T14:40:25.937 回答
1

尝试:

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

这应该适用于 32 位变量,以十六进制显示。我从未尝试使用这种技术来查看 64 位变量,但我认为它是:

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

编辑:测试了 64 位版本,它肯定适用于 Win32(我似乎记得在 GCC 上需要大写 LL ..也许)

EDIT2:如果你真的想要二进制,你最好使用其他答案之一来获得你的双精度的 uint64_t 版本,然后循环:

for ( int i = 63; i >= 0; i-- )
{
    printf( "%d", (myUint64 >> i ) & 1 );
}
于 2011-12-15T14:33:19.153 回答