Answer the question
In order to leave comments, you need to log in
How to get bit representation of type double in C++?
You need to get a bit representation of type double in C++. How can this be done with a built-in function from somewhere, or by manually getting the sign, mantissa, and exponent?
Answer the question
In order to leave comments, you need to log in
The idea is that double has 64 bits. So if we use type punning and overlay a 64-bit uint64_t double on top, we get a 64-bit integer containing the bits of the original double.
*reinterpret_cast(&a)
Next, we use the standard trick with std::bitset to translate a number into a string containing its binary representation
. And then a couple of useful facts:
- we output the same number, but with a minus sign. You can see that the sign is stored in the first bit.
- similarly, we can see in which bits the exponent is stored by looking at a, 2*a, 4*a
#include <iostream>
#include <bitset>
using namespace std;
void printBits(const double a)
{
cout << bitset<64>(*reinterpret_cast<const uint64_t*>(&a)) << endl;
}
int main()
{
const double a = 3.14;
printBits(a);
printBits(-a);
printBits(a*2);
printBits(a*4);
return 0;
}
0100000000001001000111101011100001010001111010111000010100011111
1100000000001001000111101011100001010001111010111000010100011111
0100000000011001000111101011100001010001111010111000010100011111
0100000000101001000111101011100001010001111010111000010100011111
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question