Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer representation as float, clarification needed

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?

  • 5 in binary is 0101
  • 5 can be thought of as (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?

like image 772
James Raitsev Avatar asked Jan 20 '26 23:01

James Raitsev


1 Answers

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.

like image 57
Brett Hale Avatar answered Jan 22 '26 15:01

Brett Hale