base62 (erlang_base62 v1.1.0)

View Source

Base62 encoder and decoder.

Base62 represents arbitrary binary data using a 62-character alphabet:

  • 0..25"A".."Z"
  • 26..51"a".."z"
  • 52..60"0".."9"
  • 61..63"9A" / "9B" / "9C"

The last three values (61..63) carry a leading "9" byte as a prefix flag, since the alphabet itself only spans 62 values.

Internally the encoding reuses 6-bit groups; every 3 input bytes (24 bits) maps cleanly to 4 base62 characters. Decoders recognise the "9" prefix byte in order to recover the high values 61..63.

The implementation mirrors stdlib/base64 in OTP 27+:

  • An encoder helper b62e/1 maps a 6-bit value to either a single byte (0..60) or a two-byte list (61..63) for the prefix-tagged outputs.
  • A decoder helper b62d/1 maps each input byte to a 6-bit value (or the sentinel bad or prefix).
  • The bit-syntax accumulator (writing bytes straight into the accumulator) avoids the iolist conversion the legacy implementation paid on every iteration.
  • The fast encoder path processes 3 bytes per iteration (24 bits → 4 base62 characters), the same natural alignment as base64.

Public API accepts binaries, strings (lists of bytes), and integers. Binaries round-trip through themselves; other inputs are normalised to a binary internally.

See the README.md file for an overview; this module is the source of truth.

Summary

Functions

Decode a base62 binary or string back to the original bytes.

Decode base62 data and return it as binary / list / integer. The Format is one of

Encode any data to a base62 binary.

Encode data and return the result as a flat list of bytes.

Functions

decode/1

-spec decode(binary() | string()) -> binary().

Decode a base62 binary or string back to the original bytes.

1> base62:decode(<<"aGVsbG8">>).
<<"hello">>

decode(Data, Format)

-spec decode(Data, Format) -> binary() | string() | integer()
                when Data :: binary() | string(), Format :: binary | string | integer.

Decode base62 data and return it as binary / list / integer. The Format is one of:

  • binary — the same as decode/1 (default).
  • string — return a flat list of bytes (binary_to_list).
  • integer — parse the bytes as an Erlang integer (binary_to_integer).

encode/1

-spec encode(string() | integer() | binary()) -> binary().

Encode any data to a base62 binary.

1> base62:encode(<<"hello">>).
<<"aGVsbG8">>

encode/2

-spec encode(Data, string) -> [byte()] when Data :: string() | integer() | binary().

Encode data and return the result as a flat list of bytes.