Crockford Base32 Integer Codec
Encode integers with Crockford Base32 and decode human-typed values that contain hyphens or confusable letters like O and I.
Code
ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
DECODE = {char: index for index, char in enumerate(ALPHABET)}
DECODE.update({"I": 1, "L": 1, "O": 0})
def encode(number: int) -> str:
if number < 0:
raise ValueError("number must be non-negative")
if number == 0:
return "0"
digits: list[str] = []
while number:
number, remainder = divmod(number, 32)
digits.append(ALPHABET[remainder])
return "".join(reversed(digits))
def decode(text: str) -> int:
cleaned = text.upper().replace("-", "")
if not cleaned:
raise ValueError("input is empty")
number = 0
for char in cleaned:
if char not in DECODE:
raise ValueError(f"invalid character: {char!r}")
number = number * 32 + DECODE[char]
return number
if __name__ == "__main__":
value = 123456789
token = encode(value)
print(token, decode(token))
print(decode("3N-QK8N"), decode("3NQK8N"))
Output
Captured from a sandboxed run of this snippet in the build pipeline.
3NQK8N 123456789
123456789 123456789How the snippet works
Count the functions encode and decode as the entire surface area of Crockford Base32 Integer Codec.
Repetition is confined to while number — the rest of the file is straight-line. The failure path is explicit — ValueError is raised when the guard condition holds.
Caveats
- The guard
number < 0short-circuits the flow with an earlyraisewhen its condition holds.
Applying it
The main signature reads def encode(number: int) -> str
Statements that matter
def encode(number: int) -> str:
if number < 0:
raise ValueError("number must be non-negative")
if number == 0:
return "0"
digits: list[str] = []
while number:
number, remainder = divmod(number, 32)
digits.append(ALPHABET[remainder])
return "".join(reversed(digits))
Interactive Tools for This Topic
Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- Does the code validate its input?
- It throws `ValueError` before any real work runs, via the guard `number < 0` — handle it at the call site or let it propagate deliberately.
- How do you run Crockford Base32 Integer Codec?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.