Skip to content

Computing foundations · Part 6 of 10

Unicode and UTF-8: characters, code points and bytes

A character on screen can be one or several code points, and each code point is one to four bytes in UTF-8. Learn the layers so text bugs stop surprising you.

· 2 min read

textunicode

Most text bugs come from mixing up three different things: what a person sees, what Unicode defines and what is stored as bytes.

Code points

Unicode assigns a number, called a code point, to every character: A is U+0041, é is U+00E9, the thumbs-up emoji is U+1F44D. It is a catalogue, not an encoding.

UTF-8

UTF-8 is the most common way to turn code points into bytes. It uses one to four bytes per code point. ASCII characters take one byte, so plain English text is identical to ASCII, while accented letters usually take two, many Asian characters three and emoji four.

Python
text = "é"
print(len(text))                   # 1 code point
print(len(text.encode("utf-8")))   # 2 bytes

thumbs = "👍"
print(len(thumbs), len(thumbs.encode("utf-8")))   # 1 code point, 4 bytes

What users call a character

One visible symbol can be several code points. The letter é can be written as one code point (U+00E9) or as e followed by a combining accent (U+0301). Many emoji are sequences joined together. A user-perceived character is a grapheme cluster.

Python
composed = "é"
decomposed = "é"
print(composed == decomposed)     # False, although both look identical
print(len(composed), len(decomposed))   # 1 2

Normalisation

To compare or search text correctly, convert both sides to the same normalisation form, usually NFC. Without it, two strings that look the same can differ, which breaks lookups, deduplication and security checks such as comparing usernames.

Python
import unicodedata

a = unicodedata.normalize("NFC", "é")
print(a == "é")   # True

Habits that prevent bugs

  1. Decode bytes to text as early as possible, work with text inside the program and encode at the boundary. Always state the encoding explicitly.
  2. Use UTF-8 everywhere: files, databases, HTTP headers.
  3. Do not slice strings by byte or code point when cutting text for display. Use a library that understands grapheme clusters.
  4. Be aware that length means different things in different languages: bytes, UTF-16 units or code points.
  5. Case conversion and sorting depend on the language. Use locale-aware functions where it matters.

Takeaway

Think in layers: grapheme cluster for the user, code point for Unicode, bytes for storage. Name your encoding, normalise before comparing and test with accents and emoji.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.