Reputation: 1582
I was bored and wanted to see what the binary representation of double's looked like. However, I noticed something weird on windows. The following lines of codes demonstrate
double number = 1;
unsigned long num = *(unsigned long *) &number;
cout << num << endl;
On my Macbook, this gives me a nonzero number. On my Windows machine it gives me 0.
I was expecting that it would give me a non zero number, since the binary representation of 1.0 as a double should not be all zeros. However, I am not really sure if what I am trying to do is well defined behavior.
My question is, is the code above just stupid and wrong? And, is there a way I can print out the binary representation of a double?
Thanks.
Upvotes: 1
Views: 2702
Reputation: 11582
If your compiler supports it (GCC does) then use a union. This is undefined behavior according to the C++ standard (strict aliasing rule):
#include <iostream>
int main() {
union {
unsigned long long num;
double fp;
} pun;
pun.fp = 1.0;
std::cout << std::hex << pun.num << std::endl;
}
The output is
3ff0000000000000
Upvotes: 2
Reputation: 294297
1 double is 3ff0 0000 0000 0000
. long
is a 4 byte int. On a little endian hardware you're reading the 0000 0000
part.
Upvotes: 5