Reputation: 96481
Take
int x = 5;
float y = x;
//"I know it's a float .. you know it's a float .. but take it's address
// and pretend you're looking at an integer and then dereference it"
printf("%d\n", *(int*)&y); //1084227584
Why am i seeing this number?
0101
(1.25 * 2^2)
, which means that Can be represented as:
[sign bit] - 0
[8 bits worth of exp] - 129 (129-127=2) - 1000|0001
[23 bits of .xxxxxxx] - 25 - 1100|1
Put together, i have
[sign bit][8 bits worth of exp][23 bits worth of .xxx]
0 10000001 11001000000000 //2126336
What am i missing please?
Upvotes: 3
Views: 193
Reputation: 22348
Others have pointed out it's not portable... but you know this already, and you've specified 64-bit OS X. Basically, you have the mantissa wrong. 1.25
is represented with an implicit leading bit for 1.0
. The first explicit bit of the mantissa represents 0.5
and the second bit 0.25
. So the mantissa is actually: 01000000000000000000000
.
The sign bit 0
, and biased exponent 10000001
, followed by the mantissa gives:
0x40a00000
which is 1084227584
decimal.
Upvotes: 3
Reputation: 29266
Why am i seeing this number? Because you are printing a float as an int.
I know, I know, you clearly already know this, but the bottom line is the behaviour is undefined. On your system are ints and floats the same size? Have you looked up the standards your compiler uses to store floating points?
Upvotes: 0