Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exact bit representation of a double, in C++

Let us say that we have a double, say, x = 4.3241;

Quite simply, I would like to know, how in C++, can one simply retrieve an int for each bit in the representation of a number?

I have seen other questions and read the page on bitset, but I'm afraid I still do not understand how to retrieve those bits.

So, for example, I would like the input to be x = 4.53, and if the bit representation was 10010101, then I would like 8 ints, each one representing each 1 or 0.

like image 666
Spacey Avatar asked Aug 27 '15 21:08

Spacey


1 Answers

Something like:

double doubleValue = ...whatever...;
uint8_t *bytePointer = (uint8_t *)&doubleValue;

for(size_t index = 0; index < sizeof(double); index++)
{
    uint8_t byte = bytePointer[index];

    for(int bit = 0; bit < 8; bit++)
    {
        printf("%d", byte&1);
        byte >>= 1;
    }
}

... will print the bits out, ordered from least significant to most significant within bytes and reading the bytes from first to last. Depending on your machine architecture that means the bytes may or may not be in order of significance. Intel is strictly little endian so you should get all bits from least significant to most; most CPUs use the same endianness for floating point numbers as for integers but even that's not guaranteed.

Just allocate an array and store the bits instead of printing them.

(an assumption made: that there are eight bits in a byte; not technically guaranteed in C but fairly reliable on any hardware you're likely to encounter nowadays)

like image 156
Tommy Avatar answered Sep 20 '22 06:09

Tommy