Base conversion
Convert a number to another base by repeated division; the remainders, last to first, are the digits.
In base b, the rightmost digit of n is n mod b, and the remaining digits make up n div b. So:
- Time:
O(log_b n) - Space:
O(log_b n) - Grimaldi, chapter 4
- Johnsonbaugh, chapter 5
156 in base 2: eight divisions and the answer 10011100.
DIGITS = "0123456789ABCDEF"def to_base(n, base):if n == 0:return "0"rows = []digits = ""while n > 0:q = n // baser = n % baserows.append((n, q, r, DIGITS[r]))digits = DIGITS[r] + digitsn = qreturn digits
Start
n156
digits—
The table is still empty.
Local variables
n156
base2
Orange = changed in this step
Call stack
- to_base()line 4
Step 1 of 54
Explanation
The idea
In base b, the rightmost digit of n is n mod b, and the remaining digits make up n div b. So:
- Divide
nbyb; the remainder is the next digit (from the right). - Go on with the quotient until it is zero.
The digits come out last to first, so each new digit goes in front of the string. For bases above 10, digits 10
to 15 are written A to F.
Cost
Each division gives one digit: O(log_b n) divisions.
What to watch in the trace
- The table is the repeated division you would do on paper; read the
digitcolumn from the bottom up.