Identify UTF-16 Surrogates and Code Units

How UTF-16 surrogate pairs and code units work, how to spot them, and when code-unit-based text transformations break emoji, styled letters and copy/paste.

Many text transformations, such as reversing, truncating, counting characters or converting letters into styled Unicode "fonts", quietly depend on how text is stored. In UTF-16, the encoding used internally by JavaScript, Java and many platform APIs, some characters take one 16-bit code unit and others take two, called a surrogate pair. If you can identify surrogates, you can tell in advance whether a transformation will keep your text intact or turn parts of it into broken symbols.

Short verdict: when inspecting surrogates matters

Inspecting UTF-16 code units is worth doing whenever text may contain emoji, flags, styled "bold" or "script" Unicode letters, or characters from historic and less common scripts. Its main benefit is that it explains bugs that otherwise look random: a character count that is too high, an emoji that becomes two question-mark boxes after reversal, or a post that is cut off early. The decisive tradeoff is that code units describe storage, not what a reader perceives. A tool that works correctly at the code-unit level can still split a visible character, so code-unit inspection is a diagnostic step, not a guarantee of safe output.

Plain text is preferable when the content must be searchable, read aloud by assistive technology, edited by others, or pasted into systems with strict character limits. In those cases, avoid transformations that introduce supplementary-plane characters, such as styled Unicode letters, and keep any decorative version as an optional extra rather than the only copy.

What code units and surrogates actually are

Unicode assigns each character a code point between U+0000 and U+10FFFF. UTF-16 stores text as a sequence of 16-bit code units. Code points from U+0000 to U+FFFF, known as the Basic Multilingual Plane, fit in a single code unit. Code points from U+10000 to U+10FFFF, the supplementary planes, do not fit, so UTF-16 represents each of them with two code units: a high surrogate followed by a low surrogate.

  • High (leading) surrogates: code units U+D800 to U+DBFF.
  • Low (trailing) surrogates: code units U+DC00 to U+DFFF.
  • The range U+D800 to U+DFFF is reserved for this purpose and is never assigned to a character on its own.
  • A high surrogate must be immediately followed by a low surrogate. Any surrogate that appears without its partner is a lone surrogate, and the text is not well-formed UTF-16.

The pair is calculated by subtracting 0x10000 from the code point, which leaves a 20-bit value. The top 10 bits are added to 0xD800 to form the high surrogate, and the bottom 10 bits are added to 0xDC00 to form the low surrogate. For example, U+1F600 (grinning face) minus 0x10000 is 0xF600; the top 10 bits give 0x3D, so the high surrogate is D83D, and the bottom 10 bits give 0x200, so the low surrogate is DE00.

Text | Code point(s) | UTF-16 code units | Code unit count
A | U+0041 | 0041 | 1
Γ© (precomposed) | U+00E9 | 00E9 | 1
πŸ˜€ | U+1F600 | D83D DE00 | 2
𝐀 (mathematical bold capital A) | U+1D400 | D835 DC00 | 2
πŸ‡ΊπŸ‡Έ (flag) | U+1F1FA U+1F1F8 | D83C DDFA D83C DDF8 | 4

The table shows why surrogates matter for text styling. The "bold", "italic", "script" and similar letters produced by Unicode font generators usually come from the Mathematical Alphanumeric Symbols block, which sits in a supplementary plane. Every styled letter therefore becomes a surrogate pair in UTF-16, doubling the code-unit length of the text compared with plain letters.

Three levels that are easy to confuse

Code units, code points and visible characters are different units, and many transformation problems come from treating one as another. A code unit is a 16-bit storage piece. A code point is one Unicode character value, which in UTF-16 is either one code unit or one surrogate pair. A visible character, called a grapheme cluster in Unicode terms, is what a reader sees as a single symbol, and it can contain several code points: a letter plus a combining accent, a flag made of two regional indicators, or an emoji sequence joined with zero-width joiners.

Surrogates are only a storage detail of UTF-16. The same text saved as UTF-8 uses a different byte sequence and contains no surrogates at all, which is why a well-formed surrogate pair converts cleanly to UTF-8 but a lone surrogate cannot be represented.

What a transformation actually changes

"Reverse" can mean three different operations, and only one of them is usually what a reader wants. Reversing code units, as a naive split-and-reverse does in JavaScript, swaps the order of the two halves of every surrogate pair and leaves lone surrogates that display as replacement boxes or question marks. Reversing code points keeps each pair intact but can still break visible characters: a flag such as πŸ‡ΊπŸ‡Έ becomes the regional-indicator sequence for "SU", which may display as letters or a different flag, and a base letter followed by a combining accent ends up with the accent attached to the wrong neighbor. Reversing grapheme clusters keeps each visible symbol intact and is the only one of the three that generally preserves how characters look.

// JavaScript: naive reversal splits surrogate pairs
"aπŸ˜€".split("").reverse().join("");   // "\ude00\ud83da" (two lone surrogates + "a")
[..."aπŸ˜€"].reverse().join("");        // "πŸ˜€a" (code points kept, but flags and accents can still break)

// Grapheme-aware reversal
const seg = new Intl.Segmenter("en", { granularity: "grapheme" });
[...seg.segment(text)].map(s => s.segment).reverse().join("");

"Mirror" and "font" are also ambiguous. A mirrored effect can come from substituting look-alike characters, which changes the stored text, or from CSS transforms or bidirectional display, which change only how the text is drawn. A Unicode "font" is not a font at all: it replaces each letter with a different code point, and in the case of mathematical letters, each replacement is a surrogate pair. By contrast, applying an actual typeface or bold style with CSS or a word processor leaves the stored characters unchanged, so no surrogates are introduced.

How to identify surrogates and code units

The clearest sign of surrogates is any code unit in the D800 to DFFF range. Escaped text gives this away directly: JSON and JavaScript escapes such as \ud83d\ude00 are a surrogate pair, while a code-point escape such as \u{1F600} or U+1F600 shows the same character at the code-point level. Other clues include a length count that is larger than the number of visible characters, and text that becomes garbled only around emoji or styled letters after an edit.

// JavaScript (strings are UTF-16)
const s = "πŸ˜€";
s.length;                        // 2   code units
s.charCodeAt(0).toString(16);    // "d83d"  high surrogate
s.charCodeAt(1).toString(16);    // "de00"  low surrogate
s.codePointAt(0).toString(16);   // "1f600" code point
[...s].length;                   // 1   code points
s.isWellFormed();                // true; false if a lone surrogate is present (recent engines)
# Python 3 (str counts code points, not UTF-16 units)
s = "πŸ˜€"
len(s)                                # 1
s.encode("utf-16-be").hex(" ", 2)     # 'd83d de00'
len(s.encode("utf-16-le")) // 2       # 2 code units

If you prefer a ready-made tool to writing code, useful search terms are "UTF-16 code unit viewer", "surrogate pair calculator", "Unicode code point inspector" and "grapheme cluster splitter". No specific tool was verified for this article, so check that any tool you choose shows code units and code points separately and flags lone surrogates, rather than assuming it does. Do not assume a web-based tool's privacy or data handling from its appearance; avoid pasting sensitive text unless its practices are documented.

Will the result survive copying and sharing?

Well-formed surrogate pairs normally copy and paste without trouble, because the clipboard and most destinations handle the underlying code point. Lone surrogates are the risk. When text is converted to UTF-8, which most files, web forms and network protocols use, a lone surrogate is commonly replaced with the replacement character U+FFFD, rejected with an error, or dropped, depending on the software. Python, for example, raises an error when encoding a lone surrogate to UTF-8 with default settings. A transformation that produces lone surrogates may look acceptable in the tool that created it and then degrade once shared.

Length limits are a second practical concern. Systems that measure text in UTF-16 code units count each emoji or styled letter as two, while systems that count code points or visible characters count them differently. A message that fits in one place can be truncated in another, and truncation that falls between a high and a low surrogate leaves a broken character at the end. This article does not include tests of specific platforms, so check the documentation of your destination for how it counts characters.

Accessibility and search are where supplementary-plane styling costs the most. Styled mathematical letters are distinct characters, not formatted versions of ordinary letters, so screen readers may announce them by character name, read them letter by letter, or skip them, and search and find features may not match them against plain-text queries. Behavior varies by assistive technology, browser and settings, and none was tested for this article. Where readability for everyone matters, provide a plain-text equivalent or use real formatting instead of character substitution.

Practical checklist

  • Before transforming text, check whether it contains code units in the D800 to DFFF range; if it does, avoid tools that operate on code units.
  • For reversal or truncation, prefer tools or code that work on grapheme clusters, and test with a flag, a combining accent and an emoji joined with zero-width joiners.
  • After transforming, confirm the output has no lone surrogates before copying it elsewhere.
  • Treat Unicode "font" output as decoration: keep a plain-text version for search, editing and screen readers.
  • If a destination enforces a character limit, find out whether it counts code units, code points or visible characters.

Gaps in this review

The encoding rules, ranges and examples above follow from the Unicode and UTF-16 definitions and can be checked with the snippets shown. No specific inspection tools, social platforms, editors or screen readers were tested, so claims about how a particular destination counts, displays or announces surrogate-pair characters should be confirmed in that destination's documentation or with a small test of your own.