Sub topic 6
How Base64 Represents Bytes as Text
This chapter assumes you know what a byte is, can read binary and hexadecimal numbers, and have worked with Uint8Array and TextEncoder from the earlier chapters. You will need a browser console or Node.js to run the examples.
Base64 is a way to write arbitrary bytes using only 64 safe, printable characters. It exists because many channels were built for text: email bodies, JSON fields, HTML attributes, URLs, and HTTP headers. Those channels can corrupt or reject raw bytes such as 0x00, 0xFF, or control characters. Base64 maps any byte sequence onto characters that pass through text systems unchanged, and the receiver can reverse the mapping exactly.
Base64 works on bytes, not on strings. If you want to base64-encode text, you must first turn that text into bytes with a character encoding such as UTF-8. Mixing up those two steps causes most base64 bugs in JavaScript, and later chapters cover them in detail.
The Working Model
The alphabet
Base64 uses 64 symbols, so each symbol carries exactly 6 bits (2⁶ = 64). The standard alphabet, defined in RFC 4648, assigns values like this:
| Values | Characters | Notes |
|---|---|---|
| 0–25 | `A`–`Z` | Uppercase letters |
| 26–51 | `a`–`z` | Lowercase letters |
| 52–61 | `0`–`9` | Digits |
| 62 | `+` | Has a special meaning in URLs and form encoding |
| 63 | `/` | Path separator in URLs and file systems |
| (padding) | `=` | Not a data symbol; marks a short final group |
The + and / characters cause trouble in URLs and filenames. The base64url variant swaps them for - and _, as covered in a later chapter. Everything else in this chapter applies to both variants.
Three bytes become four characters
A byte has 8 bits and a base64 character holds 6. The smallest whole number of bits that divides evenly into both is 24, which is 3 bytes or 4 characters. The encoder therefore processes input in groups of 3 bytes:
- Concatenate the 3 bytes into one 24-bit number.
- Split those 24 bits into four 6-bit groups, called sextets.
- Look up each sextet's value in the alphabet.
A worked example
The ASCII bytes for Man are 0x4D 0x61 0x6E. In binary:
M a n
01001101 01100001 01101110Regroup the same 24 bits into sixes:
010011 010110 000101 101110
19 22 5 46
T W F uMan encodes to TWFu. Decoding reverses the process. Look up each character's value, join the four 6-bit values into 24 bits, and split them back into three bytes.
Padding: When the Input Is Not a Multiple of Three
Most inputs do not divide evenly into 3-byte groups. The final group then has 1 or 2 bytes, and the encoder handles it like this:
- It pads the missing bits with zeros up to the next 6-bit boundary.
- It emits only the characters that contain real data bits.
- It appends
=so the output length is still a multiple of 4.
Here is Ma (2 bytes, 16 bits):
01001101 01100001
010011 010110 0001(00)
19 22 4
T W E =And M (1 byte, 8 bits):
01001101
010011 01(0000)
19 16
T Q = =| Bytes in final group | Data bits | Characters with data | `=` signs | Example |
|---|---|---|---|---|
| 3 | 24 | 4 | 0 | `Man` → `TWFu` |
| 2 | 16 | 3 | 1 | `Ma` → `TWE=` |
| 1 | 8 | 2 | 2 | `M` → `TQ==` |
A remainder of 0 bytes needs no final group at all, which is why base64 output never ends in ===.
Size arithmetic
For n input bytes, padded base64 output has exactly 4 * Math.ceil(n / 3) characters. That is about 33% larger than the input. Decoding goes the other way: a padded string of length L holds (L / 4) * 3 - p bytes, where p is the number of = signs.
The 33% overhead matters when you embed images as data URLs or put binary payloads into JSON. A 3 MB image becomes a 4 MB string. JavaScript stores strings internally as UTF-16 in some cases, so that string can take up to twice as much memory again.
Implementing Base64 by Hand
Every runtime ships a base64 implementation, so you should use those in real code. Writing one yourself shows exactly where the bits go and makes the later chapters easier to follow. The code below runs unchanged in a browser console or in Node.js.
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;
// Join three bytes into one 24-bit number
const triple = (b0 << 16) | (b1 << 8) | b2;
// Split into four 6-bit values
out += ALPHABET[(triple >> 18) & 63];
out += ALPHABET[(triple >> 12) & 63];
out += has1 ? ALPHABET[(triple >> 6) & 63] : "=";
out += has2 ? ALPHABET[triple & 63] : "=";
}
return out;
}
function decodeBase64(text) {
const clean = text.replace(/\s+/g, ""); // tolerate line breaks
if (clean.length % 4 !== 0) {
throw new Error("Base64 length must be a multiple of 4");
}
const padding = clean.endsWith("==") ? 2 : clean.endsWith("=") ? 1 : 0;
const out = new Uint8Array((clean.length / 4) * 3 - padding);
let o = 0;
for (let i = 0; i < clean.length; i += 4) {
let triple = 0;
for (let j = 0; j < 4; j++) {
const ch = clean[i + j];
const value = ch === "=" ? 0 : ALPHABET.indexOf(ch);
if (value === -1) {
throw new Error(`Invalid base64 character: ${ch}`);
}
triple = (triple << 6) | value;
}
if (o < out.length) out[o++] = (triple >> 16) & 255;
if (o < out.length) out[o++] = (triple >> 8) & 255;
if (o < out.length) out[o++] = triple & 255;
}
return out;
}
console.log(encodeBase64(new Uint8Array([0x4d, 0x61, 0x6e]))); // "TWFu"
console.log(encodeBase64(new Uint8Array([0x4d, 0x61]))); // "TWE="
console.log(encodeBase64(new Uint8Array([0x4d]))); // "TQ=="
// Text must become bytes first; "€" is 3 UTF-8 bytes
const euro = new TextEncoder().encode("€");
console.log(encodeBase64(euro)); // "4oKs"
const roundTrip = decodeBase64("4oKs");
console.log(new TextDecoder().decode(roundTrip)); // "€"The bit operations stay safe because the largest intermediate value is 24 bits. JavaScript bitwise operators work on 32-bit signed integers, so nothing overflows into the sign bit.
Common Errors and Gotchas
Treating base64 as encryption or compression
Base64 hides nothing. Anyone can decode it, and many people can recognize eyJ as the start of base64-encoded JSON ({") on sight. It also makes data larger. Never use it to protect secrets.
Forgetting the text-to-bytes step
Base64 has no idea what a character is. Before you encode a string, you have to choose a byte encoding for it, which is almost always UTF-8. Two systems that base64-encode the same string with different byte encodings produce different output. The next chapter shows how btoa gets this wrong for non-Latin-1 text.
Line breaks and whitespace
MIME email wraps base64 at 76 characters per line, and PEM files (certificates and keys) wrap at 64. Some decoders strip whitespace and others reject it. If you copy base64 from a .pem file or an email source, remove the line breaks before you pass it to a strict decoder.
Missing or extra padding
Many producers drop the = padding, especially in base64url tokens. The data stays unambiguous because the length modulo 4 tells you the original remainder: 2 leftover characters mean one byte, 3 mean two bytes, and 1 leftover character is always invalid. Strict decoders still require the padding, so you may need to add it back before decoding.
Non-canonical encodings
In TQ==, the character Q (value 16, binary 010000) contributes 2 data bits followed by 4 padding bits that should be zero. The string TR== uses R (010001), which has the same 2 data bits but a nonzero padding bit. A lenient decoder turns both strings into the byte M. This matters when you compare encoded strings directly, for example as cache keys or signatures. Two different strings can decode to the same bytes, so compare decoded bytes or require canonical input.
Mixing alphabets
A standard decoder that receives a base64url string fails on - and _, or skips them silently, depending on the implementation. When a value comes from a URL, a JWT, or a filename, check which alphabet it uses before you decode it.
Exercise
Encode the two bytes 0x48 0x69 (the ASCII text "Hi") to base64 by hand. Show the sextets.
Show answer
In binary the bytes are 01001000 01101001. Regrouped into sixes with zero padding bits, they become 010010 000110 1001(00), which are the values 18, 6, and 36. Those values map to S, G, and k. The input had 2 bytes, so one "=" is appended, giving "SGk=".
Exercise
How many characters long is the padded base64 encoding of 100 bytes, and how many "=" signs does it end with?
Show answer
4 Math.ceil(100 / 3) = 4 34 = 136 characters. 100 mod 3 is 1, so the final group has one byte and the string ends with "==".
Exercise
A token arrives as "TWE" with no padding. Is it valid, and how many bytes does it decode to?
Show answer
It is valid unpadded base64. Its length is 3, and 3 mod 4 is 3, which means one "=" was dropped. After restoring it to "TWE=", the string decodes to (4 / 4) * 3 - 1 = 2 bytes, 0x4D 0x61 ("Ma"). A leftover of exactly 1 character would have been invalid.