Crockford Base32 Integer Codec

Encode integers with Crockford Base32 and decode human-typed values that contain hyphens or confusable letters like O and I.

PythonData Integrity

Code

pythonsnippet
35 lines
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 123456789

How 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 < 0 short-circuits the flow with an early raise when 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

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.