0

I took a regular integer and casted it to float, what I found quite strange is that depends on the value I'm casting, after the conversion the LSB can flip a bit.

Here's an example:

Enter a number: 1313131360
FLOAT:          01001110100111001000100110010111
                        ^
                This is where the mantissa starts
INT(Original):          1001110010001001100101101100000
INT(BackFromFloat):     1001110010001001100101110000000

I took the number 1313131360 and casted it to float, and back to int, you can see the in the last line the 8th bit had turned into one.

More I noticed that if I enter the number 1313131328 it doesn't change this bit:

Enter a number: 1313131328
FLOAT:          01001110100111001000100110010110
                        ^
                This is where the mantissa starts
INT(Original):          1001110010001001100101101000000
INT(BackFromFloat):     1001110010001001100101100000000

Why is that?

user1326293
  • 923
  • 2
  • 9
  • 24

1 Answers1

0

In both cases, the conversion is doing round-to-nearest rounding, with ties round to even. In each case, the last 7 bits have to be dropped. The question is which value of bit 8 makes the float as close as possible to the original input.

01100000 is closer to 10000000 than to 00000000.

01000000 is exactly half way between 00000000 and 10000000. This invokes the tie breaker rule which picks the one that makes the least significant mantissa bit zero.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75