← Math
Math

Text, Unicode, and encoded bytes

Why did a 10-character name fail to save?

Name the unit of a text limit before counting or shortening a string.

Outcome

Tell code units, code points and UTF-8 bytes apart, check byte budgets, and shorten text without splitting a code point.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Code point
A number Unicode assigns to a character, written U+0041 for A. Emoji such as U+1F680 lie above U+FFFF.
UTF-8
An encoding that stores each Unicode scalar value in 1 to 4 bytes; lone surrogate code points are not valid UTF-8. ASCII takes 1 byte, most accented Latin letters 2, CJK characters 3 and emoji 4.
UTF-16 code unit
A 16-bit unit. JavaScript strings are sequences of them; a code point above U+FFFF takes two, called a surrogate pair.
Continuation byte
A UTF-8 byte of the form 10xxxxxx. It never starts a code point, so a cut must not land just before one.
Grapheme cluster
What a reader perceives as one character. It can be several code points, such as a letter with a combining accent or an emoji with a skin tone.
Byte budget
A storage or protocol limit counted in encoded bytes, such as a database column size or a push payload limit.

Why this matters

Form fields, database columns, push notifications and protocol headers all set limits on text, and they measure it differently. A form’s maxlength counts UTF-16 units, a storage contract may count encoded bytes or code points, and a reader counts what they see. Database types differ, so inspect the actual limit. A name that passes one check and fails another is a common production bug, and a careless cut can leave a broken character in the stored value.

This lesson assumes binary and hexadecimal and bit patterns from earlier lessons.

What a string length counts

Unicode code points identify elements of text. An encoding represents them with code units: UTF-8 uses bytes, while UTF-16 uses 16-bit units. A code point may require several units, so a string’s native length and its encoded byte size can answer different questions.

A visible character can also contain several code points, as with a combining mark or a flag. This lesson counts and truncates valid text at code point boundaries under a UTF-8 byte budget. Preserving an entire visible character requires grapheme segmentation, which is a separate boundary.

01Three lengths

Three lengths

The profile form allowed 12 characters and José Ñúñez has 10, yet the service rejected the name. Its legacy storage contract allows 12 bytes of UTF-8, and the name takes 14. A string has several lengths, and each limit counts one of them.

Predict the three lines this program prints for the name Zoë 🚀.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const name = "Zoë 🚀";

console.log(name.length); // the language's length
console.log([...name].length); // code points
console.log(new TextEncoder().encode(name).length); // UTF-8 bytes
What does the first line, the language’s own length, print?
Sizes of single characters
TextCode pointsUTF-16 unitsUTF-8 bytes
A111
é (U+00E9)112
李 (U+674E)113
🚀 (U+1F680)124
🇯🇵 (two regional indicators)248

02Budgets are bytes

Budgets are bytes

José Ñúñez has 10 code points and 10 UTF-16 units, so a form with maxlength 12 accepts it. In UTF-8, é, Ñ, ú and ñ take 2 bytes each, so the name is 14 bytes and the service’s 12-byte storage contract rejects it. Check the limit in the unit the storage uses: encode, then count bytes.

A field allows 64 UTF-16 units. What is the most UTF-8 bytes the value can take?

03Cut on a boundary

Cut on a boundary

🌸 is stored as the bytes F0 9F 8C B8. The first byte starts a code point and the other three have the form 10xxxxxx, continuation bytes. A cut placed just before a continuation byte splits the character. In TypeScript, cutting Anaïs 🌸 Dubois after 7 UTF-16 units keeps half of the surrogate pair, which encodes as the replacement character �. In Go and C++ a byte slice keeps the partial bytes, and Rust panics rather than build an invalid str.

To cut safely, walk forward by code point and stop before the next one would exceed the limit, or start at the limit and step back while the byte there is a continuation byte.

04Room for the ellipsis

Room for the ellipsis

A shortened name ends with “…”, which is one character and 3 bytes in UTF-8. Anaïs 🌸 Dubois is 18 bytes and the budget is 12.

What should be stored?

Add the ellipsis only when the name is cut. A name of exactly 12 bytes fits and is stored whole; reserving the 3 bytes in every case would shorten it for no reason.

05What a reader sees

What a reader sees

06Store the display name

Store the display name

The profile service first needs to know what its count represents: code points are different from native string length. Saving the same name then requires the storage contract’s UTF-8 byte count. When a name is too large, keep the longest code point prefix that leaves room for the visible truncation marker; a name that already fits needs neither a cut nor a marker.

In the frontend A byte counter in Next.js and Svelte Optional

When the server stores 64 bytes, maxlength="64" still accepts up to 192. Count the encoded bytes as the user types and mark the field invalid past the budget. The server checks again, because a client check can be bypassed.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useState } from "react";

const BUDGET = 64; // bytes the server stores
const encoder = new TextEncoder();

export function DisplayNameField() {
  const [name, setName] = useState("");

  const bytes = encoder.encode(name).length; // maxlength would count UTF-16 units

  return (
    <label>
      Display name
      <input
        value={name}
        onChange={(event) => setName(event.target.value)}
        aria-invalid={bytes > BUDGET}
      />
      <small>
        {bytes} / {BUDGET} bytes
      </small>
    </label>
  );
}

Check this idea later
How many code points are in 👩🏽‍💻?
A Go service cuts an initially valid UTF-8 string with s[:n], where 0 ≤ n ≤ len(s). When is the result valid UTF-8?
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.