Search code examples
floating-pointbinaryhexdecimalieee-754

Decimal Floating Point to Binary Conversion


For my computer architecture class I had to do the following simple exercise:

Convert the number -1,1 to IEEE 754 single-precision floating-point format and then convert the binary number to hexadecimal.

The solution to this exercise seems to be 0xbf8ccccd, but I have a problem understanding why the last digit of the hexadecimal number is d instead of c again.

The step I seem to be making the mistake in is when I try to convert the decimal part of the number -1.1 to binary. Specifically, I start by taking 0.1 and multiplying it by 2 and saving the integer part each time.

After a certain point I see that a certain pattern emerges. This pattern is 1100 and it occurs due to the fact that we start by 0.4 and after a couple multiplications end to 0.4 again.

Using this method I end up with the number, 0001100110011001100.

According to online converters though and as seen through the result of the exercise, the correct binary representation of 0.1 is 0.0001100110011001101.

Does anyone have any idea why the pattern gets broken at the very end, and where the mistake in my thinking process lies?

Thanks in advance!


Solution

  • Convert the number -1,1 to IEEE 754 single-precision floating-point format.

    This is not possible exactly. All IEEE 754 single-precision floating-point are some integer (up to 24 bits) times some power of 2.
    -1.1 and 0.1 is not representable as such.

    Two closest candidates to 0.1:

    0.0999999940395355224609375 
    0.100000001490116119384765625 <-- closer
    

    idea why the pattern gets broken at the very end, and where the mistake in my thinking process lies?

    When OP attempted "I start by taking 0.1 and multiplying it by 2 and saving the integer part each time.", the mathematical resulting pattern would be:

    0001100110011001100110011001100... without end.
    

    Yet as binary32 has 24 bits of significant precision, a rounded value is used

       123456789012345678901234
    0001100110011001100110011001100...
    rounds to 
    000110011001100110011001101
    

    Pattern is broken as a rounded value is used.