Sub topic 2
UTF-8: Turning Code Points into Bytes
This chapter assumes you know that a JavaScript string is a sequence of UTF-16 code units, which the previous chapter covered. It also assumes you can read hexadecimal and do basic bitwise operations (&, |, >>). Here you will see how UTF-8 turns each Unicode code point into one to four bytes, and why that byte count rarely matches string.length.
Code Points and Bytes
A code point is the number Unicode assigns to a character, written like U+20AC for €. Files, HTTP bodies, and most APIs do not store code points directly. They store bytes, and UTF-8 is the encoding they almost always use.
UTF-8 is variable-width. Small code points take fewer bytes:
| Code point range | Bytes | Byte pattern (x = payload bit) |
|---|---|---|
| U+0000 to U+007F | 1 | `0xxxxxxx` |
| U+0080 to U+07FF | 2 | `110xxxxx 10xxxxxx` |
| U+0800 to U+FFFF | 3 | `1110xxxx 10xxxxxx 10xxxxxx` |
| U+10000 to U+10FFFF | 4 | `11110xxx 10xxxxxx 10xxxxxx 10xxxxxx` |
The first byte's high bits tell a decoder how many bytes follow. Each continuation byte starts with 10. A decoder can therefore find character boundaries even if it starts reading in the middle of a stream, and ASCII text is byte-for-byte identical in UTF-8.
Encoding by Hand
The function below follows the table directly. It is for learning only. In real code you will use TextEncoder, which the next chapters cover.
function utf8Bytes(str) {
const bytes = [];
for (const ch of str) { // for...of iterates by code point
const cp = ch.codePointAt(0);
if (cp < 0x80) {
bytes.push(cp);
} else if (cp < 0x800) {
bytes.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
} else if (cp < 0x10000) {
bytes.push(
0xe0 | (cp >> 12),
0x80 | ((cp >> 6) & 0x3f),
0x80 | (cp & 0x3f)
);
} else {
bytes.push(
0xf0 | (cp >> 18),
0x80 | ((cp >> 12) & 0x3f),
0x80 | ((cp >> 6) & 0x3f),
0x80 | (cp & 0x3f)
);
}
}
return bytes;
}
const hex = (arr) => arr.map((b) => b.toString(16).padStart(2, "0")).join(" ");
console.log(hex(utf8Bytes("A"))); // "41"
console.log(hex(utf8Bytes("é"))); // "c3 a9"
console.log(hex(utf8Bytes("€"))); // "e2 82 ac"
console.log(hex(utf8Bytes("😀"))); // "f0 9f 98 80"Take € (U+20AC) as an example. In binary it is 0010 000010 101100. The top 4 bits go into 1110xxxx, which gives 0xE2. The next 6 bits go into 10xxxxxx, which gives 0x82. The last 6 bits give 0xAC.
Why the Lengths Disagree
string.length counts UTF-16 code units. UTF-8 counts bytes. The two units only agree for ASCII text:
| Character | Code point | `length` (UTF-16 units) | UTF-8 bytes |
|---|---|---|---|
| A | U+0041 | 1 | 1 |
| é | U+00E9 | 1 | 2 |
| € | U+20AC | 1 | 3 |
| 😀 | U+1F600 | 2 | 4 |
Common Mistakes
- Iterating with an index (
str[i]) splits surrogate pairs. The halves of an emoji are then treated as two separate characters. Usefor...oforcodePointAtso you work with whole code points. - Assuming one byte per character. This holds only for ASCII, and it silently truncates text when you slice byte buffers.
- Lone surrogates. A string such as
"\uD800"has no valid UTF-8 form. The hand encoder above would emit invalid bytes for it. A later chapter covers howTextEncoderhandles this case and how to repair such strings.
Exercise
Using the table and the hand encoder, what UTF-8 bytes (in hex) does "ñ" (U+00F1) produce? Also, for the string "a€😀", what are its length and its UTF-8 byte count?
Show answer
U+00F1 falls in the 2-byte range: 0xC0 | (0xF1 >> 6) = 0xC3 and 0x80 | (0xF1 & 0x3F) = 0xB1, so the bytes are "c3 b1". For "a€😀", length is 1 + 1 + 2 = 4 UTF-16 code units, and the UTF-8 byte count is 1 + 3 + 4 = 8 bytes.