floating point representation in memory is just not clear for me

My task was to get the fraction of a float then store it in an int. It seemed very easy. I did this test:

float f = 3.1415f;
printf("int pres. of float: %d\n"
       "int:                %d", *((int *)&f), 31415);

output:

int pres. of float: 1078529622

int: 31415

I changed them to base 2 to see where the 31415 is present.

0100 0000 0100 1001 0000 1110 0101 0110 - 3.1415
                    0111 1010 1011 0111 - 31415

I don't know what to do. How could I get the fraction as a simple integer?

Upvotes: 0

Views: 252

Answers (3)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

There are two key complications. One is that float is a binary floating point type, so it cannot represent 3.1415f exactly. All you have is an approximation. The closest exactly representable float value is 3.141499996185302734375.

The other is that 3.1415f is in the range of normalized numbers, which means the most significant bit of the significand, if stored, would be a non-zero binary digit, so it is not stored.

Upvotes: 1

Mats Petersson
Mats Petersson

Reputation: 129484

If we take 2.5, instead of 3.1415, because it's fairly easy to understand...

So your assumption is that 2.5 and 25 should have the same binary format. This is not the case. 25 = 0x19 = 11001. 2.5 = 10.1. Not at all the same thing.

If you feel like doing the same sort of math for 3.1415, it goes something like this:

3      = 11 (I can do that)
1/8    = 0.001  
0.1415 - 0.125 = 0.0165
1/64   = 0.000001
0.0165 - 0.015625 = 0.000875
1/2048 = 0.00000000001

And we still have some fractions of 0.1415 left to deal with at this point, but a rough result 11.00100100001.

Now, if we compare your binary output (starting at the mantissa part), and inserting a decimal point, and take into account that floating point numbers "ignore the first one":

  11.00100100001
   1.00100100001110

Seems like my scribbles above aren't completely off... ;)

Upvotes: 4

Ed Heal
Ed Heal

Reputation: 60017

Guess you need to start at https://en.wikipedia.org/wiki/IEEE_floating_point. This will tell you about the various representations of floating point numbers

Upvotes: 2

Related Questions