Sub topic 3
From Base n to Decimal
Prerequisites and the working model
This chapter assumes that you can add, multiply, use powers, and divide with remainders. You should also know basic algebra and the meaning of a positional numeral.
A number written in base \(n\) uses place values that are powers of \(n\). The rightmost digit has value \(n^0=1\). Moving left multiplies the place value by \(n\).
For a numeral with digits \(dkd{k-1}\ldots d1d0\),
\[ (dkd{k-1}\ldots d0)n = dk n^k+d{k-1}n^{k-1}+\cdots+d1n+d0. \]
Every digit must be less than the base. For example, base 5 allows only 0, 1, 2, 3, and 4.
Expand each digit by its place value
Consider \((231)_4\). Its digits occupy these places:
| Digit | Place value | Contribution |
|---|---|---|
| 2 | \(4^2=16\) | \(2\times16=32\) |
| 3 | \(4^1=4\) | \(3\times4=12\) |
| 1 | \(4^0=1\) | \(1\times1=1\) |
Add the contributions:
\[ (231)_4=2(4^2)+3(4^1)+1(4^0)=32+12+1=45. \]
The subscript 4 identifies the base. The result, 45, is normally understood to be in decimal, or base 10.
A useful shortcut is the running-value method. Start at zero. Read digits from left to right. At each step, multiply the current value by the base and add the next digit.
For \((231)_4\):
- Start with 0.
- Read 2: \(0\times4+2=2\).
- Read 3: \(2\times4+3=11\).
- Read 1: \(11\times4+1=45\).
This method avoids writing all powers when the numeral is long.
def from_base(digits, base):
symbols = "0123456789ABCDEF"
if not 2 <= base <= 16:
raise ValueError("base must be from 2 to 16")
value = 0
for ch in digits.upper():
if ch not in symbols:
raise ValueError("invalid digit")
digit = symbols.index(ch)
if digit >= base:
raise ValueError("digit is not valid in this base")
value = value * base + digit
return value
print(from_base("101101", 2)) # 45
print(from_base("213", 5)) # 58
print(from_base("2D", 16)) # 45Handling hexadecimal digits
Bases above 10 need extra symbols. In hexadecimal, base 16, the symbols are:
| Symbol | Value |
|---|---|
| A | 10 |
| B | 11 |
| C | 12 |
| D | 13 |
| E | 14 |
| F | 15 |
Therefore,
\[ (2D)_{16}=2(16)+13=45. \]
Do not treat the symbol D as a decimal digit. First replace it with its value, 13.
Checking the result
Estimate the size before calculating. Since \((231)_4\) begins with \(2\times4^2\), its value must be at least 32 and less than \(3\times4^2=48\). The answer 45 is in the correct range.
For a second check, rewrite the result using the original base. If 45 divided by 4 gives quotient 11 and remainder 1, then 11 divided by 4 gives quotient 2 and remainder 3. Reading remainders upward gives 231, confirming the conversion.
Exercise
Convert \((304)_5\) to decimal.
Show answer
\(3(5^2)+0(5^1)+4(5^0)=75+0+4=79\).