Sub topic 4
Base62 encoding and decoding
This chapter assumes you know what a number base is, can read short Python functions, and have seen the capacity estimates from the earlier chapters. Here you build the encoder and decoder that turn a numeric ID into a short code and back.
Why base62
A URL shortener needs short strings that are safe in a URL path. Base62 uses 62 symbols: the digits 0-9, the uppercase letters A-Z, and the lowercase letters a-z. These characters need no percent-encoding, so they can be pasted into chat, printed on posters, and read aloud.
Base64 is a close relative, but it adds + and /, which are awkward in URLs. Its URL-safe variant uses - and _, which can confuse readers and break word selection in some editors. Base62 avoids both problems.
Each position in a code holds one of 62 values, so a code of length n can represent 62**n distinct values.
| Length | Possible codes |
|---|---|
| 5 | 916,132,832 (about 0.9 billion) |
| 6 | 56,800,235,584 (about 57 billion) |
| 7 | 3,521,614,606,208 (about 3.5 trillion) |
Seven characters are enough for most designs. At 100 million new links per month, 3.5 trillion codes last about 2,900 years.
How encoding works
Base62 works like converting decimal to binary. You divide the number by 62 repeatedly. Each remainder is one digit, and the first remainder is the least significant digit. Because the digits come out in reverse order, you reverse them at the end.
The implementation
ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
digits = []
while n > 0:
n, r = divmod(n, 62)
digits.append(ALPHABET[r])
return "".join(reversed(digits))
def decode(s: str) -> int:
n = 0
for ch in s:
n = n * 62 + ALPHABET.index(ch)
return n
print(encode(125)) # 21
print(decode("21")) # 125
print(encode(3_521_614_606_207)) # zzzzzzz
print(decode(encode(987654321)) == 987654321) # Truedivmod(n, 62) returns the quotient and the remainder in one step. decode is Horner's method: for each character, shift the running total one place left (multiply by 62) and add the new digit.
The position of a symbol in ALPHABET is its value. So ALPHABET.index("z") is 61. The order of the alphabet is a choice, but you must never change it after launch. If you reorder it, every existing code decodes to a different number.
Common errors
- Forgetting to reverse. Without
reversed,encode(125)returns12instead of21. Round-trip tests catch this. - Zero. Without the special case, the loop never runs and
encode(0)returns an empty string. - Invalid characters.
decode("ab-c")raisesValueErrorbecause-is not in the alphabet. Validate user-supplied codes before decoding, or treat the error as a "not found". - Variable length. Small IDs produce short codes, such as
21. If you want a fixed width, pad on the left withALPHABET[0], as the hash-based generator in the next chapter does withrjust. - Slow lookup.
ALPHABET.indexscans the string, which is fine for 62 characters. For a hot path you can build a dictionary once with{ch: i for i, ch in enumerate(ALPHABET)}.
Where it fits
Base62 only converts between a number and a string. It does not decide which number to use. Counters, hashes, and random values are the options for that, and the next chapter compares them.
Exercise
Using the alphabet above, what is encode(3844)? Hint: 3844 = 62 * 62. What is the shortest code length needed to hold any ID up to 1 billion?
Show answer
3844 is 622, so the divisions give remainders 0, 0, 1 and the code is "100". For IDs up to 1 billion, 625 is about 916 million, which is too small, and 62**6 is about 56.8 billion, so 6 characters are needed.