Leading and Continuation Bytes in UTF-8

A UTF-8 character may occupy several bytes. The first byte indicates the sequence length, while following bytes follow a continuation pattern.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read one two-byte sequence
  2. Check a cut
  3. Read a multi-byte sequence through the expected length
  4. Check full validity beyond the prefix shape

Read one two-byte sequence

The character é appears as hexadecimal C3 A9. The first byte starts in binary with 110 and the next with 10. An ASCII character instead has one byte starting with zero. Hexadecimal bytes show those byte values compactly.

Check a cut

If the record ends after C3, it contains an incomplete sequence. A reader can report invalid encoding instead of trying to interpret a half-character. Text encoding round trips benefit from tests near a multibyte boundary.[1]

Read a multi-byte sequence through the expected length

The UTF-8 bytes for the euro sign are E2 82 AC. The first starts with binary 1110 and begins a three-byte sequence. Each following byte starts with 10. An isolated 82 cannot begin a valid character under the format. See hex byte notation.

E2 = 11100010 → expects two continuation bytes
82 = 10000010
AC = 10101100
Complete sequence decodes to U+20AC

Check full validity beyond the prefix shape

The format also restricts overlong encodings, surrogate code points and values beyond the Unicode range. A byte parser applying only the prefix count can accept invalid text. Test a truncated character at end of input and one split across reads.

References

  1. IETF, RFC 3629: UTF-8, a Transformation Format of ISO 10646 ↩