Sub topic 2
UTF-8: Turning Code Points into Bytes
This chapter assumes you know modern JavaScript syntax, are comfortable with bitwise operators (&, |, >>), and have read the previous chapter on how strings store UTF-16 code units. Here we look at the other side: how a Unicode code point becomes the bytes that files, HTTP bodies, and most APIs expect.
Code Points Versus Bytes
A code point is the number Unicode assigns to a character, written U+ followed by hex digits. A is U+0041, é is U+00E9, € is U+20AC, and 😀 is U+1F600. Code points run from U+0000 to U+10FFFF, so a single code point needs up to 21 bits.
An encoding decides how those numbers are stored. UTF-16, which JavaScript strings use, stores each code point as one or two 16-bit code units. UTF-8 stores each code point as one to four 8-bit bytes. The same text therefore has different lengths depending on what you count:
| Character | Code point | UTF-16 code units | UTF-8 bytes |
|---|---|---|---|
| `A` | U+0041 | 1 | 1 |
| `é` | U+00E9 | 1 | 2 |
| `€` | U+20AC | 1 | 3 |
| `😀` | U+1F600 | 2 | 4 |
String.prototype.length counts the third column. A server's Content-Length header, a database column's byte limit, or a buffer size counts the fourth.
The Four Byte Patterns
UTF-8 picks a byte count from the code point's range. It then spreads the code point's bits across fixed bit patterns:
| Code point range | Bits needed | Byte 1 | Byte 2 | Byte 3 | Byte 4 |
|---|---|---|---|---|---|
| U+0000 – U+007F | 7 | `0xxxxxxx` | |||
| U+0080 – U+07FF | 11 | `110xxxxx` | `10xxxxxx` | ||
| U+0800 – U+FFFF | 16 | `1110xxxx` | `10xxxxxx` | `10xxxxxx` | |
| U+10000 – U+10FFFF | 21 | `11110xxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |
The first byte is the lead byte. Its run of leading 1 bits tells a decoder how many bytes the sequence has in total. Every later byte is a continuation byte and always starts with 10, which leaves 6 payload bits per continuation byte.
Worked Examples by Hand
`é` (U+00E9), two bytes
0xE9 is 1110 1001. Padded to 11 bits it becomes 00011 101001. Split the bits 5 and 6:
- Lead:
110+00011=11000011= 0xC3 - Continuation:
10+101001=10101001= 0xA9
`€` (U+20AC), three bytes
0x20AC is 0010 0000 1010 1100. Split the bits 4, 6, and 6: 0010 | 000010 | 101100.
1110+0010= 0xE210+000010= 0x8210+101100= 0xAC
`😀` (U+1F600), four bytes
0x1F600 in 21 bits is 000 011111 011000 000000.
11110+000= 0xF010+011111= 0x9F10+011000= 0x9810+000000= 0x80
In UTF-16 this emoji is the surrogate pair D83D DE00. UTF-8 never uses surrogates. It encodes the real code point directly.
Writing an Encoder to See the Rules Work
The browser already ships a UTF-8 encoder, which the chapter on TextEncoder covers. Writing a small one yourself shows the rules are mechanical. A Uint8Array is an array of bytes; the next chapter covers it in detail.
function utf8Encode(str) {
const out = [];
// for...of iterates by code point, so surrogate pairs arrive joined
for (const ch of str) {
let cp = ch.codePointAt(0);
// A lone surrogate is not a valid scalar value; substitute U+FFFD
if (cp >= 0xd800 && cp <= 0xdfff) cp = 0xfffd;
if (cp < 0x80) {
out.push(cp);
} else if (cp < 0x800) {
out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
} else if (cp < 0x10000) {
out.push(
0xe0 | (cp >> 12),
0x80 | ((cp >> 6) & 0x3f),
0x80 | (cp & 0x3f)
);
} else {
out.push(
0xf0 | (cp >> 18),
0x80 | ((cp >> 12) & 0x3f),
0x80 | ((cp >> 6) & 0x3f),
0x80 | (cp & 0x3f)
);
}
}
return Uint8Array.from(out);
}
const hex = (bytes) =>
Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(" ");
console.log(hex(utf8Encode("A"))); // "41"
console.log(hex(utf8Encode("é"))); // "c3 a9"
console.log(hex(utf8Encode("€"))); // "e2 82 ac"
console.log(hex(utf8Encode("😀"))); // "f0 9f 98 80"
// Matches the built-in encoder
const s = "héllo € 😀";
console.log(hex(utf8Encode(s)) === hex(new TextEncoder().encode(s))); // true0x3f is 00111111 and masks off the low 6 bits for each continuation byte. 0xc0, 0xe0, and 0xf0 are the 110, 1110, and 11110 lead prefixes.
Measuring Byte Length Without Encoding
Sometimes you only need the size, for example to check a limit before sending. The same thresholds give the answer without building an array:
function utf8ByteLength(str) {
let n = 0;
for (const ch of str) {
const cp = ch.codePointAt(0);
n += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;
}
return n;
}
console.log("héllo €".length); // 7
console.log(utf8ByteLength("héllo €")); // 10
console.log(utf8ByteLength("😀")); // 4 (string length is 2)Lone surrogates fall in the 3-byte branch, which is correct because U+FFFD also takes 3 bytes.
Properties That Make UTF-8 Practical
ASCII compatibility. Every byte below 0x80 means the same thing as in ASCII, and multi-byte sequences never contain bytes below 0x80. Code that looks for /, \n, or " in raw bytes cannot accidentally match the middle of a multi-byte character.
Self-synchronization. A byte's top bits tell you its role. 0xxxxxxx is a complete character, 11xxxxxx starts a sequence, and 10xxxxxx continues one. If you land at a random offset, you can skip continuation bytes to reach the next character boundary.
No byte order. UTF-8 works in single bytes, so unlike UTF-16 it has no big-endian or little-endian variants. A byte order mark (EF BB BF) is allowed but unnecessary. A decoder that does not strip it will leave a stray U+FEFF at the start of your text.
Sort order preserved. Comparing UTF-8 byte strings gives the same result as comparing code points numerically.
What Makes a Byte Sequence Invalid
A decoder must reject or replace these cases:
| Problem | Example bytes | Why it is invalid |
|---|---|---|
| Unexpected continuation | `80` | Continuation byte with no lead |
| Truncated sequence | `E2 82` | Lead promised 3 bytes, got 2 |
| Overlong encoding | `C0 AF` | Encodes `/` in 2 bytes when 1 is required |
| Encoded surrogate | `ED A0 80` | U+D800 is not allowed in UTF-8 |
| Beyond U+10FFFF | `F4 90 80 80` | Larger than the Unicode maximum |
| Never-valid bytes | `C0`, `C1`, `F5`–`FF` | Can only start overlong or out-of-range sequences |
Common Errors
Truncating Bytes Mid-Character
If you cut a byte array at a fixed size, you can split a multi-byte sequence and produce an invalid tail. Use self-synchronization to back up to a boundary:
function truncateUtf8(bytes, maxBytes) {
if (bytes.length <= maxBytes) return bytes;
let end = maxBytes;
// Step back while the byte at the cut is a continuation byte (10xxxxxx)
while (end > 0 && (bytes[end] & 0xc0) === 0x80) end--;
return bytes.subarray(0, end);
}
const bytes = new TextEncoder().encode("ab€"); // 61 62 e2 82 ac
console.log(truncateUtf8(bytes, 4)); // Uint8Array [97, 98]
console.log(new TextDecoder().decode(truncateUtf8(bytes, 4))); // "ab"The loop checks bytes[end], the first byte that would be dropped. If that byte is a continuation, the character it belongs to started earlier, so the cut moves back to before that character's lead byte.
Mojibake from the Wrong Decoding
Mojibake is garbled text that appears when UTF-8 bytes are read in another encoding. Treating each byte as one Latin-1 character turns é into two characters:
const bytes = new TextEncoder().encode("é"); // c3 a9
console.log(String.fromCharCode(...bytes)); // "é"If you see é, €, or 😀 in output, something decoded UTF-8 bytes as Latin-1 or Windows-1252. This exact mistake comes back in the chapters on btoa and atob, which work on one-byte-per-character strings.
Iterating by Index
str[i] and str.charCodeAt(i) return UTF-16 code units, so a loop over indices splits surrogate pairs. Use for...of, Array.from(str), or codePointAt when you need code points.
Exercise
Encode U+00F1 (ñ) to UTF-8 by hand. Give the bytes in hex and show the bit split.
Show answer
0xF1 is 1111 0001, padded to 11 bits as 00011 110001. The lead byte is 110 + 00011 = 11000011 = 0xC3. The continuation byte is 10 + 110001 = 10110001 = 0xB1. The result is C3 B1.
Exercise
What is "a😀b".length, and what is its UTF-8 byte length? Explain both numbers.
Show answer
The length is 4 because the emoji is a surrogate pair of two UTF-16 code units, plus one each for "a" and "b". The UTF-8 byte length is 6: 1 byte for "a", 4 bytes for U+1F600 (F0 9F 98 80), and 1 byte for "b".
Exercise
A decoder receives the bytes 41 E2 82 41. Which bytes are valid, and why is the sequence broken?
Show answer
The first 41 is a valid "A". E2 is a lead byte that promises a 3-byte sequence, and 82 is a valid continuation, but the next byte 41 does not start with 10, so the sequence is truncated. A lenient decoder emits "A", one U+FFFD for the incomplete E2 82, then "A" again.
Exercise
Why does the byte C0 never appear in valid UTF-8?
Show answer
C0 is 110 00000, a 2-byte lead whose payload bits leave room only for code points below 0x40. Any code point below 0x80 must be encoded as a single byte, so a sequence starting with C0 (or C1) is always an overlong encoding and is rejected.