Coding

What Is UTF-8? How It Encodes Text, With Real Byte Examples

UTF-8 is a character encoding, a rule for turning text into bytes: it can store every Unicode character, using 1 byte for plain ASCII and 2 to 4 bytes for everything else. Because ASCII text is already valid UTF-8, English text looks the same in both, and problems only show up with accented letters, other scripts and emoji.

Characters, code points and bytes

Three layers are easy to mix up:

  • Character: what you see, such as €.
  • Code point: the number Unicode assigns to it, written U+20AC (hexadecimal 20AC, decimal 8364).
  • Encoding: the rule for storing that number as bytes. In UTF-8, U+20AC becomes the three bytes E2 82 AC.

UTF-8 is defined in RFC 3629 (November 2003), an Internet Standard (STD 63). It covers code points from U+0000 to U+10FFFF.

How UTF-8 encodes a code point

The number of bytes depends on the size of the code point. The high bits of each byte say what role the byte plays:

Code point rangeBytesBit pattern
U+0000 to U+007F10xxxxxxx
U+0080 to U+07FF2110xxxxx 10xxxxxx
U+0800 to U+FFFF31110xxxx 10xxxxxx 10xxxxxx
U+10000 to U+10FFFF411110xxx 10xxxxxx 10xxxxxx 10xxxxxx

The x positions hold the bits of the code point. Worked example for € (U+20AC). It falls in the 3-byte range. In binary, 0x20AC is 0010 0000 1010 1100 (16 bits). Split it 4 + 6 + 6:

0010     000010     101100
1110xxxx 10xxxxxx   10xxxxxx
11100010 10000010   10101100
   E2       82         AC

A few properties fall out of this design:

  • ASCII compatible. Every byte below 0x80 means exactly what it means in ASCII.
  • Self-synchronising. Continuation bytes always start with 10, so a program that lands in the middle of a character can skip forward to the next start byte.
  • No stray zero bytes. A 00 byte only ever means U+0000, so C string functions and protocols that treat zero as "end" still work.
  • Some bytes never appear. RFC 3629 states that the octet values C0, C1 and F5 to FF never appear in valid UTF-8. Code points U+D800 to U+DFFF (UTF-16 surrogates) are not allowed either.

Real byte output from Python

Run in Python 3.12. Example output:

>>> for s in ['A', 'é', '€', '😀', '日本']:
...     b = s.encode('utf-8'); print(len(s), len(b), b.hex(' '))
1 1 41
1 2 c3 a9
1 3 e2 82 ac
1 4 f0 9f 98 80
2 6 e6 97 a5 e6 9c ac

The first number is the length in characters (code points), the second the length in bytes. That gap is why string length and byte length disagree: len('naïve') is 5, but the UTF-8 bytes are 6, and in UTF-16 the same word is 10 bytes. Limits measured in bytes (database columns, HTTP headers, file name limits) can reject text that looks short.

The RFC's own examples match the same rules: the Japanese word 日本語 encodes to E6 97 A5 E6 9C AC E8 AA 9E.

Mojibake: why é becomes é

Mojibake is garbled text caused by decoding bytes with the wrong encoding. The most common case is UTF-8 read as Windows-1252 (or Latin-1):

>>> 'café'.encode('utf-8').decode('cp1252')
'café'

The two bytes of é (C3 A9) are shown as two separate Windows-1252 characters, Ã and ©. The data is not lost. Decoding the same bytes as UTF-8 brings back café. Save files as UTF-8 and declare it where the format allows, such as <meta charset="utf-8"> in HTML or Content-Type: text/html; charset=utf-8 in HTTP.

UnicodeDecodeError and what it tells you

Decoding fails when the bytes break the UTF-8 rules. These are the real errors Python 3.12 gives for three kinds of bad input:

>>> b'caf\xe9'.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: unexpected end of data
>>> b'\xc0\x80'.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 0: invalid start byte
>>> b'\xed\xa0\x80'.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 0: invalid continuation byte
  • b'caf\xe9' is "café" in Windows-1252 or Latin-1, where é is the single byte E9. In UTF-8, E9 starts a 3-byte sequence that never arrives. This message almost always means the file is not UTF-8 at all; open it with the encoding it was saved in.
  • C0 80 is an "overlong" encoding of U+0000. RFC 3629 calls out overlong forms as a security issue: a careless decoder could turn them into characters that a validation check was supposed to block.
  • ED A0 80 would be the surrogate U+D800, which UTF-8 forbids.

The errors argument controls what happens instead of raising: 'replace' substitutes U+FFFD (the � replacement character), 'ignore' drops the bad bytes, and 'backslashreplace' inserts \xNN escapes. Use these to inspect data, not to hide a wrong encoding.

The byte order mark (BOM)

Some Windows programs start UTF-8 files with EF BB BF, the UTF-8 form of U+FEFF. It does nothing useful in UTF-8 (there is no byte order to mark), but it shows up as an invisible character at the start of the text:

>>> b'\xef\xbb\xbfhi'.decode('utf-8')
'hi'
>>> b'\xef\xbb\xbfhi'.decode('utf-8-sig')
'hi'

If a CSV header or JSON key mysteriously fails to match, check for this first. Python's utf-8-sig codec strips it when reading.

UTF-8 in Python on Windows

On Windows, Python 3.12 and earlier use the system locale for files and console output unless told otherwise. On a Western European Windows install that is cp1252:

>>> import locale, sys
>>> sys.flags.utf8_mode, locale.getpreferredencoding(False)
(0, 'cp1252')

That is why open('notes.txt').read() can work on Linux and fail on Windows, and why printing an emoji to a redirected console gives UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f600'. Two fixes: always pass encoding='utf-8' to open(), or turn on UTF-8 Mode with python -X utf8 (or the environment variable PYTHONUTF8=1). Python 3.15 turns UTF-8 Mode on by default (PEP 686).

How to check a file's real bytes

When you don't know a file's encoding, look at the bytes instead of guessing. On Linux and macOS, xxd file | head prints the first bytes. In Windows PowerShell, Format-Hex does the same. Example output for a file containing "café" saved as UTF-8:

PS C:\work> Format-Hex .\cafe.txt

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   63 61 66 C3 A9                                   café

The hex column shows C3 A9, which is é in UTF-8, so the file is UTF-8. The text column on the right decodes each byte separately, which is why it shows the same mojibake as above. A single E9 byte instead would mean Windows-1252 or Latin-1, and EF BB BF at offset 0 means a BOM.

Frequently asked questions

Is UTF-8 the same as Unicode?
No. Unicode is the list of characters and the number (code point) assigned to each, such as U+20AC for the euro sign. UTF-8 is one way of storing those numbers as bytes. UTF-16 and UTF-32 store the same code points differently.
Should I save files as UTF-8 with BOM or without?
Without, unless a specific program needs the BOM. In UTF-8 the byte order mark is the three bytes EF BB BF at the start of the file. It carries no byte-order information in UTF-8, and tools that don't expect it show it as stray characters or treat it as part of the first value.
How many bytes is a character in UTF-8?
Between 1 and 4. ASCII characters (English letters, digits, basic punctuation) take 1 byte, most accented Latin, Greek and Cyrillic letters take 2, most Chinese and Japanese characters take 3, and emoji and other characters above U+FFFF take 4.
Why does my text show é instead of é?
The bytes were written as UTF-8 and read back as Windows-1252 or Latin-1. In UTF-8, é is the two bytes C3 A9, and Windows-1252 displays those two bytes as à and ©. Reopen or decode the data as UTF-8 to fix it.

Sources