UTF-8 in one paragraph
Unicode gives every character a number, its code point: A is U+0041, é is U+00E9, € is U+20AC, 😀 is U+1F600. UTF-8 is the most used way to store those numbers as bytes: ASCII characters take 1 byte, exactly as before, and everything else takes 2, 3 or 4 bytes. More than 98% of web pages use it, and JSON, HTML5 and most programming languages default to it. When text turns into é or �, the cause is almost always bytes written in one encoding and read in another.
How the bytes are built
| Code points | Bytes | Pattern | Example |
|---|---|---|---|
| U+0000 to U+007F | 1 | 0xxxxxxx | A → 41 |
| U+0080 to U+07FF | 2 | 110xxxxx 10xxxxxx | é → C3 A9 |
| U+0800 to U+FFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx | € → E2 82 AC |
| U+10000 to U+10FFFF | 4 | 11110xxx + three 10xxxxxx | 😀 → F0 9F 98 80 |
The first bits of each byte say whether it starts a character and how long it is, so a program can find character boundaries anywhere in the text. See the code points of any text in the text to Unicode tool and its bits in text to binary.
Mojibake: why "é" becomes "é"
é in UTF-8 is the two bytes C3 A9. A program that wrongly reads them as Latin-1 (ISO-8859-1) or Windows-1252, where every byte is one character, shows C3 as à and A9 as ©: é. The fix is to read the file with the right encoding, not to search and replace. The reverse mistake, Latin-1 bytes read as UTF-8, produces �, the replacement character, because E9 alone is not valid UTF-8. CSV files exported by older Excel versions and databases with a Latin-1 column are the usual suspects.
UTF-8, UTF-16 and the BOM
- UTF-16 uses 2 bytes for most characters and 4 (a surrogate pair) for the rest. JavaScript strings, Java and Windows APIs use it internally, which is why
'😀'.lengthis2in JavaScript: it counts UTF-16 units, not characters.[...'😀'].lengthis1. - The BOM (byte order mark,
EF BB BFin UTF-8) is an optional signature at the start of a file. Excel uses it to detect UTF-8 in CSV files, but it breaks some Unix tools and shebang lines; avoid it unless a program needs it. - In URLs, UTF-8 bytes are written as
%XX: see URL encoding. In Base64, text is first encoded as UTF-8 bytes.
FAQ
How many bytes does a character take in UTF-8?
1 for ASCII, 2 for most accented Latin, Greek, Cyrillic, Arabic and Hebrew letters, 3 for most other scripts (Chinese, Japanese, Hindi) and symbols like €, and 4 for emoji and rare characters.
Is UTF-8 the same as Unicode?
No. Unicode is the list of characters and their numbers; UTF-8 is one way to write those numbers as bytes (UTF-16 and UTF-32 are others).
Why does my CSV show strange characters in Excel?
The file is probably UTF-8 without a BOM and Excel opened it as the local Windows encoding. Import it choosing UTF-8, or save it with a BOM.
Does a string's length equal its number of characters?
Not always. Byte length, UTF-16 length and the number of user-perceived characters differ for accents written as two code points and for emoji.