Character Encoding and Unicode
How text becomes bytes: ASCII, Unicode code points, UTF-8 and UTF-16, grapheme clusters, mojibake and string length pitfalls.
What is it?
Computers store only bytes, so text needs an agreed mapping from characters to numbers to bytes.
- ASCII (1963) maps 128 characters (English letters, digits, punctuation, control codes) to the numbers 0–127. One byte each, but no room for é, ß, 中 or emoji. - Unicode assigns every character in every writing system a number called a code point, written like U+0041 (A) or U+1F600 (😀). There's room for 1,114,112 of them (U+0000 to U+10FFFF). - An encoding turns code points into bytes. UTF-8 uses 1 to 4 bytes per code point and is identical to ASCII for the first 128, which is why it dominates the web and files. UTF-16 uses 2 or 4 bytes and is what JavaScript, Java and Windows use internally.
What a reader sees as one character, a grapheme cluster, can be several code points: é can be one code point or e plus a combining accent, and a family emoji is several people joined by invisible joiner characters. So "how long is this string?" has at least three answers: bytes, code units or code points, and user-visible characters.
Decoding bytes with the wrong encoding produces mojibake: garbled text like café instead of café.
Explain like I'm 10
Unicode is a giant phone book that gives every character on Earth a unique number. An encoding like UTF-8 is the way you write those numbers on paper: short numbers take one box, long ones take up to four. Mojibake is reading someone's note with the wrong decoder ring.
Examples
Three different 'lengths' for one string (JavaScript)
const smile = "\u{1F600}"; // one emoji, one code point
console.log(smile.length); // 2 (UTF-16 code units)
console.log([...smile].length); // 1 (code points)
const family = "\u{1F468}\u200D\u{1F469}\u200D\u{1F467}"; // man ZWJ woman ZWJ girl
console.log(family.length); // 8 code units
console.log([...family].length); // 5 code points
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log([...segmenter.segment(family)].length); // 1 visible character
console.log(new TextEncoder().encode("café").length); // 5 bytes in UTF-8Bytes vs text, normalisation and mojibake (Python)
import unicodedata
text = "café"
data = text.encode("utf-8") # b'caf\xc3\xa9' (5 bytes)
print(len(text), len(data)) # 4 5
print(data.decode("latin-1")) # 'café' mojibake: wrong decoder
composed = "\u00e9" # é as one code point
decomposed = "e\u0301" # e + combining acute accent
print(composed == decomposed) # False, though they look identical
print(unicodedata.normalize("NFC", decomposed) == composed) # TruePython 3 separates str (code points) from bytes. Normalise strings (usually to NFC) before comparing or using them as keys if they may come from different sources.
How it works
UTF-8 encodes each code point by its size:
U+0000–U+007F: 1 byte (plain ASCII)U+0080–U+07FF: 2 bytes (most Latin accents, Greek, Cyrillic, Arabic, Hebrew)U+0800–U+FFFF: 3 bytes (most CJK characters)U+10000–U+10FFFF: 4 bytes (emoji, rarer scripts)
The leading bits of each byte say whether it starts a sequence or continues one, so a decoder can resynchronise after an error, and no multi-byte sequence ever contains an ASCII byte.
UTF-16 stores code points up to U+FFFF in one 16-bit unit and the rest as a surrogate pair of two units. It also needs a byte order (big- or little-endian), sometimes marked by a byte order mark (BOM).
Languages differ in what a "string" is: Python str is a sequence of code points; JavaScript and Java strings are UTF-16 code units; Rust String and Go strings are UTF-8 bytes (Go's len returns bytes). Grapheme clusters are defined by Unicode rules (UAX #29) and need a library or Intl.Segmenter to count.
"é" (U+00E9) through the layers
grapheme: é
code point: U+00E9
UTF-8 bytes: C3 A9 (2 bytes)
UTF-16 units: 00E9 (1 unit, 2 bytes)
Same text, read with the wrong decoder:
bytes C3 A9 as Latin-1 -> "Ã" + "©" -> "é" (mojibake)Why does it exist?
Before Unicode, every region had its own incompatible 8-bit code page (Latin-1, Shift-JIS, KOI8-R, Windows-1252), so a document often turned to garbage on another computer, and mixing languages in one file was nearly impossible. Unicode unified all scripts into one numbering, and UTF-8 made it practical by staying backward-compatible with ASCII.
When to use it
Use UTF-8 for everything that leaves your program: files, network protocols, databases, HTML (<meta charset="utf-8">). Decode bytes to text as soon as they enter, work with text inside, and encode back at the exit. Count graphemes for anything user-facing (character limits, truncation, cursor movement), bytes for storage and protocol limits.
When not to use it
Don't treat binary data (images, compressed files, encrypted bytes) as text; decoding it will corrupt it. Don't truncate or index strings by bytes or UTF-16 units when the result is shown to people: you can cut an emoji or accented letter in half. Don't guess encodings if you can declare them explicitly.
Common mistakes
Assuming one character is one byte, or that
.lengthin JavaScript counts visible characters.Opening files without an explicit encoding (e.g. Python's
open(path)on Windows may default to a legacy code page) and getting mojibake or decode errors.Truncating a string with
slice(0, n)and splitting a surrogate pair or grapheme, producing broken symbols.Comparing strings that look identical but use different normalisation forms (precomposed vs combining characters).
Using
toUpperCase/toLowerCasefor case-insensitive comparison in every language; locale rules (Turkish dotted i, German ß) need locale-aware comparison or case folding.
Practice exercises
- Easy:
Print the code point (in U+XXXX form) and UTF-8 byte count of each character in the string "Añ中" in Python and in JavaScript.
- Medium:
Write
truncate(text, maxChars)in JavaScript that never splits a grapheme cluster, usingIntl.Segmenter, and appends an ellipsis only when the text was actually cut. - Hard:
Implement a UTF-8 encoder by hand: given a code point, return its bytes using the 1–4 byte rules, and test it against
TextEncoder(JS) orstr.encode(Python) for code points in each range.
Interview questions
What is the difference between Unicode and UTF-8?
Unicode is a character set: it assigns a numeric code point to each character. UTF-8 is an encoding: a way to represent those code points as bytes (1 to 4 per code point).
What is a code point?
The unique number Unicode assigns to a character or symbol, written as U+ followed by hex digits, for example U+0041 for 'A'. Valid code points range from U+0000 to U+10FFFF.
Why is UTF-8 so widely used?
It's backward-compatible with ASCII, compact for English and most markup, has no byte-order issues, is self-synchronising, and can encode every Unicode code point. It's the default for the web, Linux and most file formats.
Why does `"😀".length` return 2 in JavaScript?
JavaScript strings are sequences of UTF-16 code units. Code points above U+FFFF, including most emoji, are stored as a surrogate pair of two code units, and .length counts code units.
What is a grapheme cluster?
What a user perceives as a single character, which can consist of several code points: a letter plus combining marks, a flag made of two regional indicators, or an emoji sequence joined with zero-width joiners.
What is mojibake and what causes it?
Garbled text caused by decoding bytes with a different encoding than they were written with, for example UTF-8 bytes read as Latin-1 turning 'é' into 'é'.
What is Unicode normalisation and why does it matter?
Converting text to a canonical form, because some characters have several representations (é as one code point, or e plus a combining accent). Without normalising (e.g. to NFC), visually identical strings may compare unequal or fail lookups.
How many bytes does UTF-8 use for ASCII, for 'é', for '中' and for an emoji?
1 byte for ASCII, 2 bytes for 'é' (U+00E9), 3 bytes for '中' (U+4E2D) and 4 bytes for emoji above U+FFFF.
What is the difference between `str` and `bytes` in Python 3?
str is a sequence of Unicode code points (text). bytes is a sequence of raw 8-bit values. You convert with .encode(encoding) and .decode(encoding), and mixing them without converting raises TypeError.
What is a BOM?
A byte order mark: the code point U+FEFF at the start of a file, used to signal byte order for UTF-16/UTF-32. In UTF-8 it's unnecessary and can cause problems (e.g. a stray character at the start of a CSV or script).