How do I use bitwise operators on a “double” on C++?

后端 未结 6 1528
遇见更好的自我
遇见更好的自我 2020-12-17 22:16

I was asked to get the internal binary representation of different types in C. My program currently works fine with \'int\' but I would like to use it with \"double\" and \"

6条回答
  •  -上瘾入骨i
    2020-12-17 22:58

    You cannot directly apply bitwise operators to float or double, but you can still access the bits indirectly by putting the variable in a union with a character array of the appropriate size, then reading the bits from those characters. For example:

    string BitsFromDouble(double value) {
        union {
            double doubleValue;
            char   asChars[sizeof(double)];
        };
    
        doubleValue = value; // Write to the union
    
        /* Extract the bits. */
        string result;
        for (size i = 0; i < sizeof(double); ++i)
            result += CharToBits(asChars[i]);
        return result;
    }
    

    You may need to adjust your routine to work on chars, which usually don't range up to 4096, and there may also be some weirdness with endianness here, but the basic idea should work. It won't be cross-platform compatible, since machines use different endianness and representations of doubles, so be careful how you use this.

提交回复
热议问题