Contents    Page-10    Prev    Next    Page+10    Index   

Number Conversion

Arabic (Indian) numerals are written in the form anan-1 ... a1a0 denoting, in number base r , the integer:

an · rn + an-1 · rn-1 + ... + a1 · r1 + a0

Factoring this expression yields:

((...(( 0 · r + an ) · r + an-1 ) · r + ... ) · r + a1) · r + a0

This suggests an algorithm for converting a number expressed by digits dndn-1 ... d1d0 to internal form in a left-to-right scan:

  1. Initialize the accumulator, num = 0.

  2. For each new digit, di , let a be the number denoted by di :
    In C, ( di - '0')
    In Lisp, (- (char-code di ) (char-code #\0))
    Then set num = num * r + a .

  3. After all digits have been processed, num is the numeric value in internal form.