Sub topic 1
Place value: what a digit really means
Prerequisites
This chapter assumes you can do long division with remainders, know the powers of 2, 3 and 10, and solve simple linear equations. You should also be comfortable reading a Python function, because the code examples use basic loops and divmod.
Place value in base 10
A digit's value depends on its position. In 507, the 5 means five hundreds because it sits in the third position from the right. Each position is worth a power of the base. In base 10, those positions are worth 1, 10, 100, 1000, and so on.
So 507 = 5 × 10² + 0 × 10¹ + 7 × 10⁰.
Writing numbers in base n
A base-n numeral uses n symbols: the digits 0 to n−1. Base 2 uses 0 and 1. Base 16 uses 0 to 9 and then A to F, where A stands for 10 and F for 15. The numeral 2D in base 16 means 2 × 16 + 13 = 45.
Write the base as a subscript to avoid confusion. 101101₂ is not the same number as 101101 in base 10.
From base n to decimal
Multiply each digit by the power of the base for its position, then add the results.
101101₂ = 1×32 + 0×16 + 1×8 + 1×4 + 0×2 + 1×1 = 45
Python can do the same job with a running value. Each step multiplies the value so far by the base and adds the next digit.
def from_base(digits, base):
value = 0
for ch in digits:
value = value * base + int(ch, 16)
return value
print(from_base("101101", 2)) # 45
print(from_base("213", 5)) # 58From decimal to base n by repeated division
Divide the number by the base and record the remainder. Repeat with the quotient until it reaches 0. The remainders, read from last to first, form the numeral.
def to_base(n, base):
symbols = "0123456789ABCDEF"
if n == 0:
return "0"
out = []
while n > 0:
n, r = divmod(n, base)
out.append(symbols[r])
return "".join(reversed(out))
print(to_base(45, 2)) # 101101
print(to_base(45, 16)) # 2DExercise
Exercise
Convert 213 in base 5 to decimal.
Show answer
2 × 25 + 1 × 5 + 3 × 1 = 50 + 5 + 3 = 58.