Sub topic 6
How Base64 Represents Bytes as Text
This chapter assumes you know what a Uint8Array is and are comfortable with binary numbers and JavaScript's bitwise operators (<<, >>, &, |). It explains how base64 works. It does not cover the built-in browser functions for it, because the next chapter does.
Why Base64 Exists
Many channels were designed to carry text, not raw bytes. JSON, URLs, email headers, HTML attributes, and environment variables are all examples. If you place arbitrary bytes into these channels, some of the bytes can be misread. A 0x00 may end a string early. A 0x0A is a newline. A value above 0x7F may be reinterpreted under some character set.
Base64 avoids this by representing any sequence of bytes with only 64 safe ASCII characters. Base64 is an encoding, so anyone can reverse it. It provides no compression and no encryption.
The Alphabet
Each base64 character stands for a 6-bit value from 0 to 63:
| Values | Characters |
|---|---|
| 0–25 | `A`–`Z` |
| 26–51 | `a`–`z` |
| 52–61 | `0`–`9` |
| 62 | `+` |
| 63 | `/` |
The = character is not part of the 64. It is used only for padding.
The 3-to-4 Grouping
Three bytes contain 24 bits. Twenty-four bits divide evenly into four 6-bit groups. Base64 therefore reads the input three bytes at a time and writes four characters for each group.
So the bytes of "Man" encode to TWFu.
Padding
When the input length is not a multiple of 3, the last group is short. The encoder fills the missing bits with zeros and writes = in place of each character that has no input behind it.
| Bytes in final group | Data characters | Padding | Example input → output |
|---|---|---|---|
| 3 | 4 | none | `Man` → `TWFu` |
| 2 | 3 | `=` | `Ma` → `TWE=` |
| 1 | 2 | `==` | `M` → `TQ==` |
Padding keeps the output length a multiple of 4. That lets a decoder work out exactly how many bytes the final group holds. Some variants drop the padding, and a later chapter on base64url shows how to put it back.
A Hand-Written Encoder
You will rarely write this yourself. Writing it once, though, shows the mechanism clearly:
const ALPHABET =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encodeBase64(bytes) {
let out = "";
for (let i = 0; i < bytes.length; i += 3) {
const has1 = i + 1 < bytes.length;
const has2 = i + 2 < bytes.length;
const b0 = bytes[i];
const b1 = has1 ? bytes[i + 1] : 0;
const b2 = has2 ? bytes[i + 2] : 0;
const triple = (b0 << 16) | (b1 << 8) | b2;
out += ALPHABET[(triple >> 18) & 63];
out += ALPHABET[(triple >> 12) & 63];
out += has1 ? ALPHABET[(triple >> 6) & 63] : "=";
out += has2 ? ALPHABET[triple & 63] : "=";
}
return out;
}
console.log(encodeBase64(new Uint8Array([0x4d, 0x61, 0x6e]))); // "TWFu"
console.log(encodeBase64(new Uint8Array([0x68, 0x69]))); // "aGk="
console.log(encodeBase64(new Uint8Array([0x4d]))); // "TQ=="Notice that the input is a Uint8Array. Base64 operates on bytes, not on characters. To base64-encode text, you must first decide which bytes represent that text, which in practice means UTF-8. The next chapter shows what goes wrong when that step is skipped.
Size Overhead
The output length is 4 * Math.ceil(n / 3) characters for n input bytes, which makes it about 33% larger than the input. A 3 MB image becomes roughly 4 MB of base64 text.
Common Errors
- Treating base64 as text-aware. Base64 sees only bytes. The same text can produce different base64 output under different character encodings.
- Stripping
=carelessly. Some decoders reject unpadded input. - Mixing alphabets. Standard base64 uses
+and/. URL-safe base64 uses-and_. A decoder that expects one alphabet may reject the other.
Exercise
Encode the two bytes of "Ma" (0x4D, 0x61) by hand. Then work out how many base64 characters 10 bytes of input produce.
Show answer
The bits are 01001101 01100001. Adding two zero bits gives 010011 010110 000100, which is the values 19, 22 and 4, or the characters T, W and E. One "=" fills the missing fourth character, giving "TWE=". For 10 bytes, 4 ceil(10 / 3) = 4 4 = 16 characters, and the output ends in "==" because the final group holds only one byte.