| home | send comment | send link | add bookmark |

Base conversion

by Stephen R. Schmitt


Numbers and bases

A number in a system with base N may only consist of digits that are less than N. For base 10, the largest digit is 9. Generally, in base N, a number M can be represented as:

MN = akNk + ak-1Nk-1 + ... + a1N1 + a0

This can be rewritten as:

MN = a0 + N·(a1 + N·(a2 + N·(a3 + ... )))

The algorithm for obtaining the digits ai uses integer division and remainder (modulo) operations:

a0 = M modulo N 
M  = M / N
a1 = M modulo N 
M  = M / N
a2 = M modulo N  
M  = M / N 
a3 = M modulo N 
  .
  .

For example, to convert 1710 into base 8:

a0 = 17 modulo 8 = 1 
M  = 17 / 8      = 2 
a1 =  2 modulo 8 = 2
M  =  2 / 8      = 0 {all done}

Then 1710 = 218

The algorithm can be implemented recursively to create a string representing the number M in base N. A recursive implementation avoids the difficulties caused by producing a sequence of digits in the reverse order. The program shown below accomplishes this.

Zeno source code

Zeno 1.2 is an interpreter for the Zeno programming language. It is an easy to learn and is suitable for educational purposes.

program

    put conversion( 4047, 16 )
    put conversion( 4047, 8 )
    put conversion( 4047, 4 )
    put conversion( 4047, 2 )
    
end program

% convert number base 10 to a different base by recursion
function conversion( num, bas : int ) : string

    var s : string

    if num < bas then               % recursion done             
        s := digit( num )
    else                           
        s := conversion( num div bas, bas ) & digit( num mod bas )
    end if

    return s

 end function

 % convert a digit into a character
 function digit( x : int ) : string

     var s : string
     assert x >= 0                  % must be positive digit

     if x < 10 then                 % use digits
         s[1] := chr( ord('0') + x )
     else                           % use letters
         s[1] := chr( ord('A') + x - 10 )
     end if

     s[2] := chr(0)
     return s

end function

Sample output

FCF
7717
333033
111111001111


Copyright © 2005, Stephen R. Schmitt