Algorithmintro
UTF-16
Also called UTF-16 encoding, surrogate pairs.
Encode each scalar value below 10000 as one 16-bit unit and each larger one as a surrogate pair that carries 10 bits each of the value minus 10000. Surrogates themselves are not encoded.
- Time
- Θ(n) worst · best
- Space
- O(1) extra
- Where
- n = the number of 16-bit code units
- Model
- Word RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
UTF-16 is the encoding form of Unicode that writes each scalar value as one or two 16-bit code units. A scalar value below 10000 (hexadecimal) is one unit with the same value. A larger one becomes a surrogate pair: a high surrogate in D800..DBFF and a low surrogate in DC00..DFFF, which together carry the 20 bits of the value minus 10000. The surrogate code points are reserved for this use, so they are never characters and are not encoded themselves. Windows, Java, JavaScript and .NET keep their strings in UTF-16.
In plain words
The first version of Unicode had room for 65,536 characters, and many systems stored each character in 16 bits. When Unicode grew to more than a million code points, these systems needed a way to store the new characters without changing their 16-bit strings.
The answer was to set aside 2,048 of the 16-bit values. A character beyond the first 65,536 is written as two of these values: the first one comes from one block of 1,024 and the second one from another block of 1,024. Together they give 1,024 times 1,024 choices, which covers the new characters. Every other character is one 16-bit value, as before.
Because the two blocks are different, a program always knows whether a 16-bit value is a whole character, the first half of a pair or the second half.
The problem
Encoding. The input is a scalar value : and not in D800..DFFF. The output is its UTF-16 code unit sequence (D91).
Decoding. The input is a sequence of code units. A well-formed sequence is a concatenation of single units that are not surrogates and of pairs of a high surrogate followed by a low surrogate. The output is the sequence of scalar values. An unpaired surrogate, that is, a high surrogate without a low one after it or a low surrogate without a high one before it, is ill-formed. A strict decoder reports it, and a replacing decoder writes one U+FFFD REPLACEMENT CHARACTER for it.
Bytes. To store or send UTF-16, each unit becomes two bytes. UTF-16BE puts the high byte first and UTF-16LE the low byte first. The label "UTF-16" without a byte order allows a byte order mark, U+FEFF, at the start (RFC 2781, section 3.2). Its bytes FE FF mean big-endian and FF FE little-endian.
The algorithm
UTF16-ENCODE(c)- 1
if c < 0x10000 then return [c] - 2
v <- c - 0x10000 - 3
return [0xD800 + (v >> 10), 0xDC00 + (v AND 0x3FF)] UTF16-DECODE(U[0..n-1])- 4
out <- empty list; i <- 0 - 5
while i < n do - 6
u <- U[i] - 7
if u < 0xD800 or u > 0xDFFF then append u to out; i <- i + 1 - 8
else if u <= 0xDBFF and i + 1 < n and 0xDC00 <= U[i + 1] <= 0xDFFF then - 9
append 0x10000 + ((u - 0xD800) << 10) + (U[i + 1] - 0xDC00) to out; i <- i + 2 - 10
else append 0xFFFD to out; i <- i + 1 - 11
return out
Line L2 maps 10000..10FFFF onto the 20-bit range 0..FFFFF. Line L3 puts the high 10 bits into the high surrogate and the low 10 bits into the low surrogate. Line L10 handles a low surrogate that starts a step and a high surrogate that is not followed by a low surrogate. A strict decoder raises an error there instead.
The byte layer of the implementation turns each two bytes into a unit and then runs UTF16-DECODE. An odd final byte is a truncated unit and gives one more U+FFFD. If the unit before it is a high surrogate, Python counts the 3 bytes as one truncated sequence and writes one U+FFFD for them, and the implementation does the same.
Example
Encode U+1F600 GRINNING FACE. Line L2 gives , which is 0000111101 1000000000 in 20 bits. The high 10 bits are 3D and the low 10 bits are 200, so line L3 returns D83D DE00. In UTF-16BE the bytes are D8 3D DE 00, and in UTF-16LE they are 3D D8 00 DE.
| code point | UTF-16 code units |
|---|---|
| U+0041 | 0041 |
| U+20AC | 20AC |
| U+FFFD | FFFD |
| U+10000 | D800 DC00 |
| U+1F600 | D83D DE00 |
| U+10FFFF | DBFF DFFF |
Decode the units 0041 D83D 0042 DE00 D83D DE00 with replacement. The first unit is U+0041. D83D is a high surrogate followed by 0042, which is not a low surrogate, so it gives U+FFFD. Then comes U+0042. DE00 is a low surrogate at the start of a step, so it gives U+FFFD. The last two units form a pair, and line L9 gives . The output is U+0041 U+FFFD U+0042 U+FFFD U+1F600, the same as Python's bytes.decode("utf-16-be", "replace").
Correctness
The map of lines L1 to L3 is a bijection from the scalar values onto the well-formed one-character sequences. Values below 10000 that are not surrogates map to themselves. The values 10000..10FFFF map to pairs, because has exactly 20 bits and each half of it fits the 1,024 values of one surrogate block. The decoder keeps the invariant that the unit at is never the second unit of a pair that starts before . So line L9 reads exactly the pairs, line L7 the single units, and line L10 exactly the unpaired surrogates, one at a time. Each step moves by 1 or 2, so the loop stops after at most steps. The full proof is in proofs/correctness.md.
Proof: UTF-16 is a bijection from scalar values to well-formed unit sequences, and the decoder inverts itfull
Claim. (a) UTF16-ENCODE (lines L1 to L3) maps each Unicode scalar value to a well-formed UTF-16 code unit sequence of length 1 or 2, and this map is a bijection between the scalar values and the well-formed sequences of one character. (b) For every sequence of code units, UTF16-DECODE (lines L4 to L11) stops after at most iterations. If is well-formed, it outputs the scalar values that encodes. If not, it outputs one U+FFFD for each unpaired surrogate and decodes the rest.
Setup. A code unit is an integer in . A high surrogate is a unit in D800..DBFF and a low surrogate a unit in DC00..DFFF. By D91 of the core specification, a well-formed UTF-16 sequence of one character is either one unit that is not a surrogate or a high surrogate followed by a low surrogate. A sequence is well-formed if it is a concatenation of such pieces. A surrogate that is not part of such a pair is unpaired: a high surrogate that is not followed by a low surrogate, or a low surrogate that does not follow a high surrogate of a pair.
Lemma 1 (encoding). If , line L1 returns the one unit , which is not a surrogate because is a scalar value. If , then is in , a 20-bit number. Its high 10 bits are in , so the first unit of line L3 is in D800..DBFF. Its low 10 bits are in , so the second unit is in DC00..DFFF. So the output is well-formed.
The map is injective. One-unit outputs are the values themselves. Two-unit outputs carry the 20 bits of without loss, and . It is onto. A non-surrogate unit is the scalar value and encodes to itself. A pair gives in , and is a scalar value of 10000..10FFFF that encodes to .
Lemma 2 (one step). Let and . One iteration of the loop of line L5 does one of three things.
- is not a surrogate (line L7). It outputs and moves by 1.
- is a high surrogate and exists and is a low surrogate (line L8). Line L9 outputs , which is the scalar value that the pair encodes by Lemma 1, and moves by 2.
- Otherwise is a low surrogate, or a high surrogate without a low surrogate after it (line L10). It outputs U+FFFD and moves by 1.
Invariant. At the start of each iteration, is not the second unit of a pair whose first unit is before . This holds for . Case 2 skips both units of the pair. Cases 1 and 3 move past one unit that is not a high surrogate followed by a low surrogate, so the unit at the new cannot be the second unit of a pair that starts at the old .
Proof of (b). Each iteration raises by 1 or 2, so the loop stops after at most iterations, at line L11. By the invariant, case 3 meets a low surrogate only when that surrogate does not follow a high surrogate of a pair, so it is unpaired. A high surrogate meets case 3 only when no low surrogate follows it, so it is unpaired too. Conversely, every unpaired surrogate is reached as in some iteration, because the scan skips only the second units of pairs, and it then falls into case 3. So the output has one U+FFFD per unpaired surrogate. If is well-formed, there are no unpaired surrogates, every piece is handled by case 1 or case 2, and by Lemma 1 the output is the sequence of encoded scalar values. In strict mode, case 3 raises an error at offset instead.
Byte layer. UTF-16BE and UTF-16LE write each unit as two bytes, high byte first or low byte first. A byte string of even length maps one to one to a unit sequence, so the claim carries over. For odd length, the last byte is a truncated unit. The decoder outputs one more U+FFFD for it, and when the unit before it is a high surrogate, which then cannot have a partner, it counts the 3 bytes as one truncated sequence. This matches Python's codecs and changes nothing for well-formed input, which always has even length.
Complexity
In the word-RAM model, encoding takes time per code point and decoding time for units, with extra space besides the output.
| claim | value |
|---|---|
| units per code point | 1 below U+10000, 2 from U+10000 to U+10FFFF |
| bytes per code point | 2 or 4 |
| decoding time |
Finding the th code point of a UTF-16 string takes time in general, as in UTF-8, because of the pairs. Indexing by unit is , and that is what String.charAt in Java and string indexing in JavaScript do.
Properties
- Self-synchronizing. Single units, high surrogates and low surrogates are three disjoint ranges, so from any unit at most one step back reaches the start of a code point.
- Not order-preserving. Comparing UTF-16 strings unit by unit does not sort them by code point. U+FF61 is the unit FF61, but U+10000 is D800 DC00, and D800 is smaller than FF61. The test
test_unit_order_is_not_code_point_orderchecks this. A comparison can fix it by mapping the units D800..DFFF above the units E000..FFFF before it compares them. - Length in units. Java's
String.length()and JavaScript'slengthcount units, so "😀".length is 2. The functionlength_in_code_unitscomputes this value, and the testtest_length_in_code_unitschecks it. - Byte order. The two byte forms differ, so files and protocols need a label or a byte order mark. UTF-8 has no such issue.
- Size. Text in the BMP, including Chinese, Japanese and Korean, takes 2 bytes per character. ASCII text takes twice the space it takes in UTF-8.
Variants and improvements
- UCS-2. The 16-bit form of the first Unicode versions, with no surrogate pairs. It covers only the BMP. Old code that treats each unit as a character works like UCS-2 and breaks supplementary characters into two.
- WTF-16, or potentially ill-formed UTF-16. Windows file names, Java strings and JavaScript strings may contain unpaired surrogates. Software that must keep such data exactly treats the units as opaque and converts it with a lossless form such as WTF-8.
- UTF-32. One 32-bit unit per scalar value. It gives access to the th code point but takes 4 bytes per character.
- CESU-8. The UTF-16 units of a string, each encoded as if it were a code point in a 3-byte UTF-8 form. Used inside some databases. It is not UTF-8.
When to use it
Use UTF-16 when the platform already uses it: the Windows API, Java, JavaScript, .NET, and libraries built on them. Converting at each call costs time and can lose unpaired surrogates. For files and network data, prefer UTF-8, which has no byte order and is smaller for most markup and source code. Never use a unit count as the number of characters that a user sees. For that, count extended grapheme clusters with the rules of text segmentation.
Pitfalls
- Splitting a pair. Cutting a string after a fixed number of units can leave a high surrogate at the end of one piece and a low surrogate at the start of the next. Both pieces are then ill-formed.
- Unpaired surrogates from other sources. A JavaScript string such as "\uD800" is valid in the language but cannot be encoded in UTF-8. Python's
encode("utf-8")raises an error for it. The testtest_unpaired_surrogateschecks the replacing and strict decoders on such input. - Encoding a surrogate code point. UTF16-ENCODE must reject D800..DFFF. Otherwise a lone U+DC00 and the second half of a pair would look the same. The test
test_surrogates_are_not_scalar_valueschecks this. - The byte order mark. U+FEFF at the start of a UTF-16 stream is a signature, not text. Strip it when you read with the plain "UTF-16" label, and do not add it when the label is UTF-16BE or UTF-16LE.
- Odd byte counts. A UTF-16 byte stream with an odd length is truncated. The test
test_odd_lengthschecks the treatment of the final byte.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/utf-16/. The authors are listed in prov/7HJ2KD.jsonl.
"""UTF-16 encoding and decoding, as in The Unicode Standard 16.0.0, section 3.9 (D91), and RFC 2781.
The core works on 16-bit code units. The byte layer (UTF-16BE and UTF-16LE) puts each code
unit in two bytes. An unpaired surrogate code unit is ill-formed; the decoder replaces each
one with U+FFFD, as Python's bytes.decode("utf-16-be", "replace") does.
"""
REPLACEMENT = 0xFFFD
class UTF16Error(ValueError):
"""Raised by strict decoding. start and end are offsets in the input (code units or bytes)."""
def __init__(self, start: int, end: int) -> None:
super().__init__(f"ill-formed UTF-16 at {start}..{end - 1}")
self.start = start
self.end = end
def is_high(u: int) -> bool:
return 0xD800 <= u <= 0xDBFF
def is_low(u: int) -> bool:
return 0xDC00 <= u <= 0xDFFF
def encode_code_point(c: int) -> list[int]:
"""Return the UTF-16 code units of the scalar value c."""
if not 0 <= c <= 0x10FFFF or 0xD800 <= c <= 0xDFFF:
raise ValueError(f"{c:#x} is not a scalar value")
if c < 0x10000: # @line L1
return [c]
v = c - 0x10000 # @line L2
return [0xD800 + (v >> 10), 0xDC00 + (v & 0x3FF)] # @line L3
def encode_units(s: str) -> list[int]:
"""Encode a str of scalar values as a list of code units."""
out: list[int] = []
for ch in s:
out.extend(encode_code_point(ord(ch)))
return out
def decode_units(units: list[int], errors: str = "replace") -> list[int]:
"""Decode code units to code points; each unpaired surrogate gives one U+FFFD."""
out: list[int] = []
n = len(units)
i = 0 # @line L4
while i < n: # @line L5
u = units[i] # @line L6
if not 0xD800 <= u <= 0xDFFF: # @line L7
out.append(u)
i += 1
elif is_high(u) and i + 1 < n and is_low(units[i + 1]): # @line L8
out.append(0x10000 + ((u - 0xD800) << 10) + (units[i + 1] - 0xDC00)) # @line L9
i += 2
else: # @line L10
if errors == "strict":
raise UTF16Error(i, i + 1)
out.append(REPLACEMENT)
i += 1
return out # @line L11
def encode(s: str, byteorder: str = "big") -> bytes:
"""Encode s as UTF-16BE (byteorder "big") or UTF-16LE ("little"), with no byte order mark."""
return b"".join(u.to_bytes(2, byteorder) for u in encode_units(s))
def decode(data: bytes, errors: str = "replace", byteorder: str = "big") -> str:
"""Decode UTF-16BE or UTF-16LE bytes.
A final odd byte is a truncated code unit and gives one U+FFFD. Like Python, a high
surrogate followed only by such a byte gives one U+FFFD for the 3 bytes.
"""
n = len(data)
units = [int.from_bytes(data[k:k + 2], byteorder) for k in range(0, n - 1, 2)]
# A final high surrogate is never part of a pair. If an odd byte follows it, the
# 3 bytes are one truncated sequence.
merge_tail = n % 2 == 1 and len(units) > 0 and is_high(units[-1])
body = units[:-1] if merge_tail else units
try:
out = decode_units(body, errors)
except UTF16Error as e:
raise UTF16Error(2 * e.start, 2 * e.end) from None
if n % 2 == 1:
start = n - 3 if merge_tail else n - 1
if errors == "strict":
raise UTF16Error(start, n)
out.append(REPLACEMENT)
return "".join(map(chr, out))
def length_in_code_units(s: str) -> int:
"""The length that Java and JavaScript report: 2 for each supplementary code point."""
return sum(2 if ord(ch) >= 0x10000 else 1 for ch in s)
test_utf_16.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/utf-16/. The authors are listed in prov/7HJ2KD.jsonl.
# The oracle is Python's codec: str.encode("utf-16-be") and bytes.decode("utf-16-be").
# Written against Python 3.14, unicodedata.unidata_version 16.0.0. UTF-16 does not depend
# on the Unicode version.
import itertools
import random
from utf_16 import UTF16Error, decode, decode_units, encode, encode_code_point, length_in_code_units
UNITS = [0x0000, 0x0041, 0xD7FF, 0xD800, 0xDBFF, 0xDC00, 0xDFFF, 0xE000, 0xFFFD, 0xFFFF]
def oracle_strict(b: bytes):
try:
return b.decode("utf-16-be")
except UnicodeDecodeError as e:
return (e.start, e.end)
def mine_strict(b: bytes):
try:
return decode(b, "strict")
except UTF16Error as e:
return (e.start, e.end)
def check(b: bytes) -> None:
assert decode(b) == b.decode("utf-16-be", "replace"), b.hex(" ")
assert mine_strict(b) == oracle_strict(b), b.hex(" ")
def test_check_values() -> None:
table = {0x41: [0x0041], 0xE9: [0x00E9], 0x20AC: [0x20AC], 0x10000: [0xD800, 0xDC00],
0x1F600: [0xD83D, 0xDE00], 0x10FFFF: [0xDBFF, 0xDFFF]}
for c, units in table.items():
assert encode_code_point(c) == units
assert decode_units(units) == [c]
def test_encode_against_codec() -> None:
points = [0, 0x7F, 0x80, 0x7FF, 0x800, 0xD7FF, 0xE000, 0xFFFF, 0x10000, 0x10FFFF]
rng = random.Random(1)
points += [rng.choice([rng.randrange(0xD800), rng.randrange(0xE000, 0x110000)]) for _ in range(5000)]
for c in points:
assert encode(chr(c)) == chr(c).encode("utf-16-be")
assert encode(chr(c), "little") == chr(c).encode("utf-16-le")
assert decode(encode(chr(c))) == chr(c)
assert decode(encode(chr(c), "little"), byteorder="little") == chr(c)
def test_surrogates_are_not_scalar_values() -> None:
for c in (0xD800, 0xDBFF, 0xDC00, 0xDFFF, 0x110000, -1):
try:
encode_code_point(c)
raise AssertionError("must reject")
except ValueError:
pass
def test_unpaired_surrogates() -> None:
assert decode_units([0xD800, 0x0041]) == [0xFFFD, 0x41]
assert decode_units([0xDC00, 0xD800]) == [0xFFFD, 0xFFFD]
assert decode_units([0xD800, 0xD800, 0xDC00]) == [0xFFFD, 0x10000]
# The surrogatepass handler of Python keeps lone surrogates as code points.
assert bytes.fromhex("D800 0041").decode("utf-16-be", "surrogatepass") == "\ud800A"
def test_all_unit_sequences_up_to_three() -> None:
for k in range(1, 4):
for t in itertools.product(UNITS, repeat=k):
check(b"".join(u.to_bytes(2, "big") for u in t))
def test_odd_lengths() -> None:
for t in itertools.product(UNITS, repeat=2):
b = b"".join(u.to_bytes(2, "big") for u in t)
for extra in (b"\x00", b"\xdc", b"\xd8"):
check(b + extra)
check(b[:2] + extra)
check(b[:1])
def test_random_bytes() -> None:
rng = random.Random(2)
pool = [0x00, 0x41, 0xD8, 0xDB, 0xDC, 0xDF, 0xE0, 0xFF]
for _ in range(5000):
check(bytes(rng.choice(pool) for _ in range(rng.randrange(1, 11))))
def test_length_in_code_units() -> None:
s = "a€😀"
assert len(s) == 3
assert length_in_code_units(s) == 4 == len(s.encode("utf-16-be")) // 2
def test_unit_order_is_not_code_point_order() -> None:
a, b = "。", "\U00010000"
assert ord(a) < ord(b)
assert encode_units_list(a) > encode_units_list(b)
def encode_units_list(s: str) -> list[int]:
out = []
for ch in s:
out.extend(encode_code_point(ord(ch)))
return out
History
Unicode 1.0 (1991) was a 16-bit code, and early adopters such as Windows NT and Java stored each character in one 16-bit unit, the form now called UCS-2. When it became clear that 65,536 code points were not enough, Unicode 2.0 (1996) and an amendment to ISO/IEC 10646 defined UTF-16, which reserves 2,048 code points of the BMP as surrogates. The pairs give exactly 1,048,576 more code points, planes 1 to 16, which is why the Unicode codespace ends at 10FFFF. RFC 2781 (2000) registered the labels UTF-16, UTF-16BE and UTF-16LE for Internet use, and RFC 3629 (2003) limited UTF-8 to the same range.
References
- The Unicode Consortium, The Unicode Standard, Version 16.0.0, 2024, Chapter 3: Section 3.8 Surrogates (D71 to D75) and Section 3.9 Unicode Encoding Forms (D76 Unicode scalar value, D91 UTF-16)
- P. Hoffman and F. Yergeau, UTF-16, an encoding of ISO 10646, RFC 2781, February 2000, Section 2 (UTF-16 definition, 2.1 Encoding UTF-16, 2.2 Decoding UTF-16) and Section 3 (Labelling UTF-16 text, 3.2 Byte order mark)
- The Unicode Standard, Version 16.0.0, core specification (online), Chapter 3, Sections 3.8 and 3.9; Chapter 23, Section 23.6 Surrogates Area
- Python documentation, codecs, Standard Encodings (utf_16, utf_16_be, utf_16_le) and Error Handlers
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7HJ2KD Edit this page History Report an error Markdown