Converting between decimal and binary

• Binary-to-decimal conversion:
The basic algorithm: Use the above formula

x = d0 + 2(d1+2(d2+.....+2(dk-1+2dk)...))

and using decimal arithmetic.

1 x <- dk   (move leftmost digit to x)
2 i <- k-1 (set index to next digit)
3 while i > 0 do
4     x <- di +2x (compute inner product)
5     i <- i - 1 (decrement index, end while loop)
6 stop[**]

NOTE: If this conversion algorithm were performed in some other number system (such as octal - base 8, or quinary - base 5) then the resulting representation would be IN THAT BASE system:

For base 5 (quinary) to decimal:

x = d0 + 5(d1+5(d2+.....+5(dk-1+5dk)...))
• Decimal-to-binary conversion:

is based on repeated division by 2 in decimal, so that the binary digits generated from right to left (using decimal arithmetic):

Assume representation to be converted is associated with the variable x:

1 s <- 0 (starting from rightmost digit)
2 while x != 0 do
3     ds <- x mod 2 (get remainder of divide by 2)
4     x <- floor(x/2) (reset x to quotient)
5     s <- s + 1 (set up for next digit)
6 stop[**]

WHY DOES THIS WORK?

Because - the "mod" function gives us back the remainder of the division of the number by 2, and this is the low order digit. That is:

(dk2k + dk-12k- 1+....+d121+d020) mod 2 =

(2 (dk2k-1 + dk-12k- 2+....+d120) + d020) mod 2 =

d020

Through the repeated application of the mod function to the quotient of the previous step, we successively get the successive digits of the binary representation.

For more help on number conversions see:

A Base Converter

The Implementation of Base Conversion

CS1104 Main Page
Last Updated 2002/02/04
© L.Heath, 2000, modified by J.A.N. Lee