Search code examples
algorithmdecimalieee-754

Conversion of decimal fraction to floating-point binary reprecentation


Let's assume that we have normalized floating point numbers with an exponent range of [-3,3] and a precision of 4 bits. Below you see 4 decimal numbers and the corresponding binary representation. How can I convert these decimal numbers to binary? How to go from binary to decimal I know, but not vice versa.

0.11 (decimal) = 1.000 * 2^-3 (binary)
3.1416 (decimal) = 1.101 * 2^1 (binary)
2.718 (decimal) = 1.011 * 2^1 (binary)
7 (decimal) = 1.110 * 2^2 (binary)

Solution

  • Just go out from the definition of both mantissa and exponent. The exponent is the easiest part. The mantissa is nothing else than a sum of two's negative powers: 1 + ½ + ¼ + ⅛ … , some of which are multiplied to one, some — to zero.

    To determine exponent's value, find the biggest power of two that, when being divided (multiplied for numbers in [0,1) ) to, gives a value in range [1, 2).

    For 0.11, it is -4 (not -3 as you state), as 0.11 * 2⁴ = 1.76. For 3.1416, it is +1 because 3.1416/2¹ = 1.5708

    Then you'll have a number m in range [1,2) left to convert to a binary fraction. Start with r = "1." as a result, then subtract 1 from m and multiply it by two. If the result is more than one, write "1" to the end of r and subtract 1 from m, otherwise write "0" to the end of r. Continue multiplying by two and optionally subtracting 1 from m, while simultaneously writing "0" and "1" to r depending whether you had to subtract 1 or not. Stop when you have enough digits in mantissa.

    I guess you can figure out how to do desired rounding mode yourself.