Skip to content
Basics

UTF-16 and UTF-32

Fixed and variable width encodings used in modern environments.

Time Complexity
O(1)
Space Complexity
O(2-4 bytes)

Interactive Visualization

UTF-16 (JavaScript/C#)
0xD83D
0xDE80

Uses 2 or 4 bytes. Emojis use "Surrogate Pairs".

UTF-32 (Python Ints)
0x0001F680

Always 4 bytes. Simple indexing, heavy memory.

Technical Guide

UTF-16 uses either 2 or 4 bytes per character and is the internal format for JavaScript and Java. UTF-32 uses exactly 4 bytes for every single character. UTF-32 is easier for O(1) indexing but consumes vast amounts of memory. UTF-16 is a middle ground but introduced 'Surrogate Pairs', where one logical character is represented by two 16-bit storage units.

Logical Phases

  • 1
    UTF-16 maps the Basic Multilingual Plane (common chars) to 2 bytes.
  • 2
    Extended characters (Emojis) use two 16-bit units (Surrogates).
  • 3
    UTF-32 maps every Unicode code point directly to a 32-bit integer.
  • 4
    Choosing UTF-32 for algorithms where memory is cheap but indexing speed is critical.

Implementation

// UTF-16 surrogate pair
'🚀'.length; // 2 units

Expert Pitfalls

UTF-16 is variable-width just like UTF-8, but often mistaken for fixed-width.