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

Base conversion

by Stephen R. Schmitt

number base 10
N =
number base N


Contents

  1. About
  2. The source code
  3. Discussion

1. About

This Java Script calculator converts an integer from base 10 to a given base. To operate the calculator, enter the base 10 number and the base for conversion. Press the Compute button to obtain the solution. On invalid entries, a popup window will display an error message.

Return to Contents


2. The source code

The Java Script source code for this program can be viewed by using the View|Source command of your web browser.

You may use or modify this source code in any way you find useful, provided that you agree that the author has no warranty, obligations or liability. You must determine the suitability of this source code for your use.

Return to Contents


3. Discussion

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.

Return to Contents


AbCd Classics - free on-line books


Copyright © 2004, Stephen R. Schmitt