InternationalisationVol. 23 · i18n
0 / 0

Shelves / Internationalisation

IN·01

Unicode and Text

What a "character" really is: bytes, code units, code points and the grapheme clusters users see; how UTF-8, UTF-16 and UTF-32 encode Unicode and why UTF-8 won; combining marks, Indic conjuncts and emoji sequences; normalisation forms; mojibake and how it happens; what length, indexing, slicing and reversing mean in Python, JavaScript, Java, Kotlin, Swift and Go; with a lab that measures the same strings in four units and truncates Telugu safely.

20 topics · ~14 min read · 16-question quiz
Updated Suggest a correction

Start here: how long is "नमस्ते"?

Ask a programmer how long a string is and they'll call len(). Ask a user and they'll count what they see. For English those agree. For most of the world's writing they don't. The lab measured eight strings four ways:

Text UTF-8 bytes UTF-16 code units Code points Graphemes (what users see)
English (Lemon rice) 10 10 10 10
Hindi नमस्ते 18 6 6 3
Telugu పెరుగు అన్నం (curd rice) 34 12 12 6
Tamil தயிர் சாதம் (curd rice) 31 11 11 7
👍🏽 (thumbs up, medium skin tone) 8 4 2 1
👨‍👩‍👧 (family) 18 8 5 1
🇮🇳 (flag of India) 8 4 2 1
Crème brûlée 15 12 12 12

Four different answers to "how long is it?", and each is correct for a different purpose. A database column limit counts one, a JavaScript .length another, a notification preview should count a third. The bug in waiting: TiffinBox truncated notification previews to 10 code points, and the Telugu text ended on a virama (U+0C4D, a sign that joins two consonants), leaving a broken half-letter on screen. Cutting at 12 bytes was worse still. Only cutting at grapheme boundaries produced whole letters.

This chapter builds the model that explains every number in that table.

How deep to go

Volume 17 defines six mastery levels. For Unicode and text:

Level What you can do
L1 Explain characters, code points and UTF-8; always use UTF-8
L2 Handle multilingual input and output without mojibake; count and truncate correctly
L3 Explain code units, surrogates, grapheme clusters and normalisation, and how each language's string type behaves
L4 Diagnose encoding and normalisation bugs from hex dumps and logs
L5 Set text-handling policy for a system: encodings at every boundary, normalisation, limits, validation
L6 Contribute to text-processing libraries, fonts or input methods for complex scripts

From bytes to characters: four layers

Text in a computer has four layers. Every text bug is a confusion between two of them.

Layer What it is Example for 👍🏽
bytes what's stored and sent F0 9F 91 8D F0 9F 8F BD (8 bytes in UTF-8)
code units the fixed-size unit of an encoding: 8 bits in UTF-8, 16 in UTF-16, 32 in UTF-32 4 UTF-16 units: D83D DC4D D83C DFFD
code points Unicode's numbers for characters U+1F44D (thumbs up), U+1F3FD (skin tone modifier)
grapheme clusters what a user sees as one character 1: 👍🏽

Before Unicode

Early computers used ASCII: 128 codes (7 bits) for English letters, digits, punctuation and control codes. Every other language invented its own 8-bit code page: Latin-1 (ISO-8859-1) for Western Europe, Windows-1252, ISCII for Indian scripts, Shift-JIS for Japanese, and dozens more. The same byte meant different letters in different code pages, so a file was only readable if you knew which one it used, and one document couldn't mix scripts.

Unicode: one number per character

Unicode gives every character of every script one number, a code point, written U+ followed by hex: U+0041 is A, U+0928 is Devanagari न, U+0C2A is Telugu ప, U+0B9A is Tamil ச, U+0627 is Arabic ا, U+1F44D is 👍. The range is U+0000 to U+10FFFF, organised into 17 planes of 65,536 code points. Plane 0, the Basic Multilingual Plane (BMP, U+0000–U+FFFF), holds almost all living scripts; the others hold emoji, historic scripts, rare CJK characters and private-use areas.

Unicode also records properties for each code point: its script (Devanagari, Latin, Cyrillic), its general category (letter, mark, number, punctuation), its case mappings, its bidi class (chapter 06) and more. Libraries and regular expressions rely on these properties.

Unicode separates the character (an abstract letter) from the glyph (its drawn shape, chosen by the font). One code point can have many glyphs (Arabic letters change shape by position in a word); several code points can make one glyph (स + ् + त = स्त).

Encodings: code points as bytes

A code point is a number; an encoding turns it into bytes.

Encoding Code unit Bytes per code point Notes
UTF-8 8 bits 1–4 ASCII-compatible; the web, Linux, JSON, most files and APIs
UTF-16 16 bits 2 or 4 Java, JavaScript, C#, Windows APIs, Android's Java strings
UTF-32 32 bits 4 fixed width; used internally, rarely stored

UTF-8 uses the high bits of each byte to say how long the sequence is:

Code points Bytes Pattern Covers
U+0000–U+007F 1 0xxxxxxx ASCII
U+0080–U+07FF 2 110xxxxx 10xxxxxx Latin accents, Greek, Cyrillic, Arabic, Hebrew
U+0800–U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx Indic scripts, CJK, most of the BMP
U+10000–U+10FFFF 4 11110xxx + three 10xxxxxx emoji, rare characters

That is why Crème brûlée is 15 bytes (12 code points, three of them two bytes each) and Telugu takes 34 bytes for 12 code points (eleven three-byte letters and marks plus one one-byte space). UTF-8 has properties that made it win: ASCII text is unchanged; no byte of a multibyte sequence looks like an ASCII character, so / and \0 are safe; you can find character boundaries from any position (continuation bytes start 10); and byte order doesn't matter.

UTF-16 stores BMP code points in one 16-bit unit and the rest as a surrogate pair: two units from the reserved range D800–DFFF. 👍 (U+1F44D) becomes D83D DC4D. Code that treats each 16-bit unit as a character can split a pair, producing a lone surrogate that's not valid text and often renders as �.

A byte order mark (BOM, U+FEFF at the start of a file) tells UTF-16 readers the byte order. In UTF-8 it's unnecessary, but Windows tools sometimes write one; a stray BOM breaks CSV headers, shell scripts and JSON parsers.

Grapheme clusters: what users see

A grapheme cluster is the unit a user perceives as one character, and the unit the cursor moves by, backspace deletes (mostly), and selection snaps to. Unicode's extended grapheme cluster rules (UAX #29) define the boundaries. Things that join code points into one cluster:

  • Combining marks: e + U+0300 (combining grave) = è; Devanagari vowel signs such as े (U+0947) attach to the consonant before them.
  • Indic conjuncts: a consonant + virama (U+094D in Devanagari, U+0C4D in Telugu, U+0BCD in Tamil) + consonant forms a conjunct. Since Unicode 15.1 the rules keep these together as one cluster, as users expect.
  • Emoji modifiers: 👍 + 🏽 (skin tone).
  • Zero-width joiner sequences: 👨 + ZWJ + 👩 + ZWJ + 👧 = 👨‍👩‍👧.
  • Regional indicator pairs: 🇮 + 🇳 = 🇮🇳.
  • Variation selectors: ❤ + U+FE0F requests the emoji (colour) presentation ❤️.
  • Hangul syllables built from jamo.

Grapheme rules change with Unicode versions (on the lab machine, Python 3.13 used Unicode 15.1 while Node.js 22 carried Unicode 16.0), which is why the lab's Tamil count (7) depends on the library version, and why counting is best left to a maintained library rather than hand-written rules.

Normalisation: the same text, different code points

Some characters can be written two ways. è is either one code point (U+00E8, precomposed) or two (U+0065 e + U+0300 combining grave). They look identical but compare unequal. Unicode defines normalisation forms that pick one:

Form What it does Use
NFC compose where possible the default for storage and comparison; what most keyboards produce
NFD decompose fully some processing (e.g. stripping accents); macOS file names historically
NFKC compose, and replace compatibility characters (fi → fi, ① → 1, full-width A → A) identifiers, usernames, search keys
NFKD decompose with compatibility replacements search and matching

The lab built Crème both ways: NFC is 43 72 E8 6D 65, NFD is 43 72 65 300 6D 65. As strings they're unequal; after NFC normalisation they're equal. Text arrives in mixed forms (macOS file names, copy-paste from PDFs, different keyboards), so normalise at the boundary (usually to NFC) before storing, comparing, hashing or using text as a key. Use NFKC for identifiers such as usernames, where tiffin (full-width) shouldn't be a different user from tiffin.

Normalisation doesn't solve look-alikes across scripts (Latin o and Cyrillic о stay different); chapter 07 deals with those.

Mojibake: decoding with the wrong encoding

Bytes don't carry their encoding. When a program decodes UTF-8 bytes as Windows-1252 (or Latin-1), every multibyte sequence turns into several Latin characters. The lab:

  • पनीर became पनीर
  • Crème brûlée became Crème brûlée

à followed by another accented character is the classic sign of UTF-8 read as Latin-1. The reverse error (Latin-1 bytes read as UTF-8) gives �, the replacement character, because the bytes aren't valid UTF-8. Worst is double encoding: mojibake that's saved, re-encoded as UTF-8 and stored, which can only be repaired by reversing each step exactly.

Mojibake happens at boundaries: a database connection with the wrong client encoding, a CSV opened by a spreadsheet that assumes the system code page, an HTTP response without charset=utf-8, an email header, a log shipper. The rule: UTF-8 everywhere, declared explicitly at every boundary: Content-Type: text/html; charset=utf-8, <meta charset="utf-8">, database ENCODING 'UTF8' with client_encoding UTF8, encoding="utf-8" when opening files in Python, and a BOM only where Excel needs one for CSV.

Strings in programming languages

Each language's string type counts and indexes in one of the four layers. Knowing which avoids most bugs.

Language String stores length counts Indexing gives Grapheme-aware tool
Python 3 code points code points a code point regex module's \X, grapheme package
JavaScript UTF-16 code units a code unit Intl.Segmenter
Java / Kotlin (JVM, Android) UTF-16 code units (length()) a char (code unit) BreakIterator, codePointCount for code points
Swift (iOS) UTF-8 internally count = grapheme clusters Character (a grapheme); no integer indexing built in
Go bytes (UTF-8) len = bytes a byte utf8.RuneCountInString for code points; uniseg for graphemes
Rust bytes (UTF-8) len() = bytes slicing on byte offsets, panics mid-character unicode-segmentation crate
C / C++ bytes bytes a byte ICU
SQL (PostgreSQL) encoded bytes length() = code points; octet_length() = bytes — —

Consequences:

  • Reversing a string by code points breaks combining marks and emoji (the skin tone ends up before the hand); by UTF-16 units it creates invalid surrogates. Reverse by graphemes, or better, don't.
  • Slicing for a preview must cut at grapheme boundaries, then append an ellipsis. The lab's grapheme-aware cut of పెరుగు అన్నం సిద్ధంగా ఉంది ("curd rice is ready") to 10 graphemes kept పెరుగు అన్నం సిద్ధంగా whole.
  • Length limits must name their unit: a database varchar(10) counts code points; a byte budget (SMS, push payloads, Kafka message size, HTTP headers) counts bytes; a UI limit ("name up to 30 characters") should count graphemes. The lab's 12-code-point Telugu string was rejected by varchar(10), though users see only six letters.
  • Regular expressions need Unicode mode: \w in many engines matches only [A-Za-z0-9_] unless Unicode is on, rejecting నమస్తే as a "word". Use property classes (\p{L} letters, \p{M} marks, \p{Script=Telugu}) and, in JavaScript, the u or v flag.
  • Case conversion is language-dependent and can change length: "ß".upper() is SS; Turkish dotted and dotless i (chapter 02).

Fonts, rendering and input

Getting the code points right is half the job; the user has to see and type them.

  • Fonts: no font covers all of Unicode. Platforms fall back from font to font; a missing glyph shows as "tofu" (□). Ship or specify fonts for your scripts (Noto covers almost all of them) and test on real devices; the lab machine's fallback fonts, for example, render Telugu wider than a phone would.
  • Shaping: complex scripts need a shaping engine (HarfBuzz on Android, Chrome and Linux; Core Text on Apple platforms) to choose glyph forms, conjuncts and mark positions. You never place Indic or Arabic glyphs yourself; you hand text to the platform's text system.
  • Line breaking follows Unicode rules (UAX #14): Thai and Japanese have no spaces between words, so breaking needs dictionaries; don't split text on spaces to wrap it.
  • Input methods (IMEs) compose text in stages: a Telugu or Japanese keyboard sends provisional text that is replaced as the user types. Code that validates or reformats on every keystroke can break composition; in the browser, respect compositionstart/compositionend.

Text policy for a system

  1. UTF-8 everywhere: files, databases, APIs, logs, queues. Declare it at every boundary.
  2. Decode at the edge, encode at the edge: inside the program, work with text (code points), not bytes.
  3. Normalise to NFC when text enters the system; NFKC (plus case folding) for identifiers.
  4. Name the unit of every limit: bytes for storage and protocols, graphemes for UI.
  5. Truncate at grapheme boundaries, never in the middle of a cluster.
  6. Reject or strip invalid text at the boundary: lone surrogates, non-characters, unexpected control characters (including bidi controls, chapter 06).
  7. Test with real text: Indic scripts, Arabic, emoji sequences, combining accents, and very long words.

Common traps

  • Assuming one byte or one char is one character.
  • Counting length with the wrong unit for a limit.
  • Cutting strings for previews without grapheme awareness.
  • Comparing text without normalising.
  • Leaving encodings implicit at a database connection, file or HTTP boundary.
  • \w and [a-zA-Z] in validation, rejecting most of the world's names.
  • Reversing or uppercasing strings by hand.

Lab: one string, four lengths

Setup. Python 3.13 on the lab machine with Unicode 15.1 data (unicodedata) and the regex module (2026.9.29), whose \X matches one extended grapheme cluster. UTF-16 length is computed as the UTF-16-LE byte count divided by two. Nothing here is simulated: these are the same counts a phone, a browser or a database would compute with the same Unicode version.

Results: lengths

Text UTF-8 bytes UTF-16 units Code points Graphemes
Lemon rice 10 10 10 10
नमस्ते 18 6 6 3
పెరుగు అన్నం 34 12 12 6
தயிர் சாதம் 31 11 11 7
👍🏽 8 4 2 1
👨‍👩‍👧 18 8 5 1
🇮🇳 8 4 2 1
Crème brûlée 15 12 12 12

Results: truncating a notification preview to "10 characters"

Input: పెరుగు అన్నం సిద్ధంగా ఉంది ("curd rice is ready").

Cut by Result Problem
10 code points పెరుగు అన్ ends on U+0C4D TELUGU SIGN VIRAMA: a dangling half-conjunct
12 bytes, decoded with replacement పెరు four letters; a byte cut mid-letter would show � without careful decoding
10 graphemes పెరుగు అన్నం సిద్ధంగా whole letters, as the user expects

Results: normalisation and mojibake

  • Crème in NFC: 43 72 E8 6D 65; in NFD: 43 72 65 300 6D 65. Equal as strings: False. Equal after NFC: True.
  • UTF-8 bytes decoded as Windows-1252: पनीर → पनीर; Crème brûlée → Crème brûlée.

What it shows

  • "Length" has four meanings. For English they coincide, which is why English-only testing hides the bugs.
  • Indic scripts use 3 bytes per code point in UTF-8 and several code points per visible letter: a 34-byte, 12-code-point string is six letters to a Telugu reader.
  • Emoji sequences are the extreme case: one visible symbol, five code points, eighteen bytes.
  • Truncation must be grapheme-aware; code-point cuts produce broken conjuncts and byte cuts produce broken characters.
  • Normalisation is invisible until a comparison, a unique index or a hash disagrees.

Try it yourself

  1. In a browser console, compare 'పెరుగు అన్నం'.length, [...'పెరుగు అన్నం'].length and [...new Intl.Segmenter('te', {granularity: 'grapheme'}).segment('పెరుగు అన్నం')].length. Which layer does each count?
  2. In Kotlin, compare "👍🏽".length with "👍🏽".codePointCount(0, "👍🏽".length); in Swift, print "👍🏽".count.
  3. Create two files named Crème on macOS and Linux, copy them between machines, and compare the bytes of the names with ls | xxd.
  4. Write a truncate(text, n) that cuts at grapheme boundaries and appends … only when it actually cut; test it on every string in the table.
  5. Take a UTF-8 CSV with Hindi text, open it in a spreadsheet without a BOM, then with one, and note what changes.

Revision sheet: Unicode and text

Key ideas

  • Four layers: bytes, code units, code points, grapheme clusters. Every text bug confuses two of them.
  • Unicode assigns code points U+0000–U+10FFFF; encodings (UTF-8, UTF-16, UTF-32) turn them into bytes.
  • UTF-8: 1 byte for ASCII, 2 for most alphabetic scripts, 3 for Indic and CJK, 4 for emoji; ASCII-compatible and self-synchronising.
  • UTF-16: one unit in the BMP, a surrogate pair above it; JavaScript, Java and Kotlin count units.
  • Graphemes: combining marks, conjuncts, emoji modifiers, ZWJ sequences, flags. Swift counts these; others need a segmenter.
  • Normalise (NFC for storage and comparison, NFKC for identifiers) at the boundary.
  • Mojibake comes from undeclared or wrong encodings at boundaries; declare UTF-8 everywhere.
  • Name the unit of every limit; truncate at grapheme boundaries.

Numbers to remember

  • 1,114,112 code points; ~155,000 assigned.
  • Telugu curd rice: 34 bytes, 12 code points, 6 graphemes; family emoji: 18 bytes, 8 UTF-16 units, 5 code points, 1 grapheme.

Glossary

  • Code point: Unicode's number for a character, U+XXXX.
  • Code unit: the fixed-size piece of an encoding (8, 16 or 32 bits).
  • Surrogate pair: two UTF-16 units encoding one code point above U+FFFF.
  • Grapheme cluster: what a user perceives as one character.
  • Virama: an Indic sign that suppresses a consonant's vowel and joins it to the next consonant.
  • ZWJ: zero-width joiner, U+200D, which combines emoji into one.
  • NFC / NFD / NFKC / NFKD: Unicode normalisation forms.
  • Mojibake: text garbled by decoding with the wrong encoding.
  • BOM: byte order mark, U+FEFF at the start of a file.