Since 54 = 16 × 3 with a remainder of 6:
digit[ 0 ] = 54 mod 16 = 6,
number = 54 div 16 = 3
Algorithm: Convert a number from base 10 to base B repn |
---|
place = 0; number = number to be converted while (number > 0 ) { digit[place] = number mod B ; number = number div B ; place = place + 1 ; } |
The first execution of the loop body calculates the digit for place 0, the rightmost digit. Notice what has happened: the first execution says that:
5410 = 3 × 161 + 6 × 160
The first execution of the loop body calculates the digit for place 0, the rightmost digit. The next execution yields the digit for place 1. This calculates digit[1] = 6 mod 16 = 6 and number = 3 div 16 = 0. After this the algorithm is done, and the result is 5410 = 0x36
If you are enthused about this (could happen) you might wish to use mathematical induction to prove that the algorithm is correct. A normal person would just prefer another example.