The Base64 algorithm

Published

Base64 is defined in RFC 4648. The idea fits in one sentence: regroup the input bits from 8-bit bytes into 6-bit numbers, and write each number as a character.

Why 6 bits?

2⁶ = 64, so a 6-bit number can be represented by one of 64 characters. The least common multiple of 8 and 6 is 24, so the algorithm works on blocks of 24 bits = 3 bytes = 4 characters.

The index table

Values Characters
0–25 A–Z
26–51 a–z
52–61 0–9
62 +
63 /
(padding) =

The full table with binary values is on the Base64 characters page.

Encoding in four steps

  1. Take the next 3 bytes of input.
  2. Concatenate their 24 bits.
  3. Split into four 6-bit numbers.
  4. Look up each number in the table.

If fewer than 3 bytes remain at the end, append zero bits to complete the last 6-bit group, and add = for each missing byte: one remaining byte gives two characters + ==, two remaining bytes give three characters + =.

Detailed walkthroughs: encoding step by step and decoding step by step.

Output length

For n input bytes, padded Base64 has exactly:

4 × ⌈n / 3⌉ characters

Without padding it is ⌈4n / 3⌉. Decoding goes the other way: bytes = 3 × length / 4 − number of "=" characters.

Pseudo-code

ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

encode(bytes):
  out = ""
  for i in 0, 3, 6, ... < len(bytes):
    b0, b1, b2 = bytes[i], bytes[i+1] or 0, bytes[i+2] or 0
    n = (b0 << 16) | (b1 << 8) | b2
    out += ALPHABET[(n >> 18) & 63] + ALPHABET[(n >> 12) & 63]
    out += (i+1 < len) ? ALPHABET[(n >> 6) & 63] : "="
    out += (i+2 < len) ? ALPHABET[n & 63]        : "="
  return out

decode(text):
  n = 0; bits = 0; out = []
  for c in text without "=":
    n = (n << 6) | ALPHABET.indexOf(c); bits += 6
    if bits >= 8: bits -= 8; out.push((n >> bits) & 255)
  return out

Variants

The algorithm is always the same; standards differ only in the two last characters of the alphabet, padding rules and line breaks. For example Base64URL uses - and _ so that values are safe in URLs.

Comments (0)

Questions, ideas or a bug in “The Base64 algorithm”? Leave a comment, rate the tool, or reply to others.

No comments yet. Be the first to share your feedback!

Leave a comment

Rate this tool:
Esc
↑ ↓ move↵ openEsc close