Sub topic 5
Converting Fractions Between Decimal and Binary
Prerequisites and the Working Model
Assume you know decimal and binary place values, basic binary addition, and powers of two. A binary fraction uses powers of two to the right of the binary point:
\[ (101.101)_2 =1\cdot2^2+0\cdot2^1+1\cdot2^0 +1\cdot2^{-1}+0\cdot2^{-2}+1\cdot2^{-3} \]
Therefore,
\[ (101.101)2=4+1+\frac12+\frac18=5.625{10} \]
The first position after the point has weight \(2^{-1}\), the next has weight \(2^{-2}\), and so on.
Decimal Fraction to Binary
To convert a decimal fraction to binary, repeatedly multiply the fractional part by 2. Record the integer part at each step. Continue with the new fractional part.
Convert \(0.625_{10}\):
| Step | Value multiplied by 2 | Recorded bit | New fraction |
|---|---|---|---|
| 1 | \(0.625\times2=1.25\) | 1 | 0.25 |
| 2 | \(0.25\times2=0.5\) | 0 | 0.5 |
| 3 | \(0.5\times2=1.0\) | 1 | 0 |
Reading the recorded bits from top to bottom gives:
\[ 0.625{10}=0.1012 \]
For a number with an integer part, convert the integer part separately and place the binary fraction after the point. Thus:
\[ 13.625{10}=1101.1012 \]
The process stops when the fractional part becomes zero. If a fractional part repeats, the binary representation also repeats.
For example, converting \(0.1_{10}\) produces:
\[ 0.1{10}=0.0001100110011\ldots2 \]
The pattern 0011 repeats. This happens because \(1/10\) has a factor of 5 in its reduced denominator, and powers of 2 cannot remove that factor.
from fractions import Fraction
def decimal_fraction_to_binary(value, places=16):
value = Fraction(value)
bits = []
fraction = value
for _ in range(places):
fraction *= 2
if fraction >= 1:
bits.append("1")
fraction -= 1
else:
bits.append("0")
if fraction == 0:
break
return "0." + "".join(bits)
print(decimal_fraction_to_binary("0.625")) # 0.101
print(decimal_fraction_to_binary("0.1")) # 0.0001100110011001Binary Fraction to Decimal
Convert each binary digit using its place value and add the results:
\[ (0.1101)_2 =1\cdot2^{-1}+1\cdot2^{-2}+0\cdot2^{-3}+1\cdot2^{-4} \]
\[ =\frac12+\frac14+\frac1{16}=0.8125_{10} \]
A finite binary fraction always has a denominator that is a power of two after simplification. Consequently, a decimal fraction has a finite binary representation only when its reduced denominator contains no prime factors other than 2.
Exercise
Exercise
Convert \(0.375{10}\) to binary and convert \(0.0112\) back to decimal.
Show answer
\(0.375\times2=0.75\), then \(0.75\times2=1.5\), then \(0.5\times2=1\), so \(0.375{10}=0.0112\). Also, \(0.0112=2^{-2}+2^{-3}=0.25+0.125=0.375{10}\).