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
- Take the next 3 bytes of input.
- Concatenate their 24 bits.
- Split into four 6-bit numbers.
- 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.
دیدگاهها (0)
سؤال، ایده یا باگی در «The Base64 algorithm» دارید؟ دیدگاه بگذارید، به ابزار امتیاز دهید یا به دیگران پاسخ دهید.
هنوز دیدگاهی ثبت نشده است. اولین نفری باشید که نظر خود را به اشتراک میگذارد!