UTF-8 — One to Four Bytes per Character
Unicode gives 😀 the number 128,512, but a file is just bytes. Storing every character in 4 bytes would make English text four times bigger than ASCII. UTF-8 solves this elegantly: common characters take one byte, rarer ones take more. Today almost the entire web is UTF-8.
The rule
UTF-8 spends 1 to 4 bytes per code point; ASCII stays one byte.
The number of bytes depends only on how big the code point is:
| Code point range | Bytes | Examples |
|---|---|---|
| U+0000 – U+007F | 1 | A, 7, space |
| U+0080 – U+07FF | 2 | é, ñ, Greek, Arabic |
| U+0800 – U+FFFF | 3 | अ, ₹, €, most Chinese characters |
| U+10000 – U+10FFFF | 4 | 😀, rare historic scripts |
The leading bits of every byte say what role it plays:
0xxxxxxx 1-byte character (plain ASCII)
110xxxxx 10xxxxxx start of 2, then 1 continuation
1110xxxx 10xxxxxx 10xxxxxx start of 3, then 2 continuations
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx start of 4, then 3 continuationsThis design gives UTF-8 its best properties. Any ASCII file is already valid UTF-8. A byte beginning 10 is never the start of a character, so a program dropped into the middle of a text can find the next character boundary. And because UTF-8 is read one byte at a time, it has no endianness problem.
When UTF-8 bytes are decoded with the wrong encoding, each multi-byte character turns into several junk symbols: café shows up as café. That garbling has a name, mojibake.