Algorithm · Strings · O(n) in code points

UTF-8 and UTF-16 encoding

How one Unicode code point becomes 1–4 UTF-8 bytes or 1–2 UTF-16 code units, and why string length depends on what you count.

The full derivation, edge cases and exercises are in the lesson Strings in memory: code units, code points and graphemes. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Text is a sequence of code points (U+0000 … U+10FFFF). UTF-8 spends 1 byte on ASCII and up to 4 bytes on the rest, with the leading bits of each byte saying how many follow. UTF-16 uses one 16-bit unit for code points up to U+FFFF and a surrogate pair above it.

That is why C# and Java string lengths count UTF-16 units, Python’s len counts code points, and C++ std::string counts bytes, and why none of them count what a reader sees as one character (a grapheme cluster).

Steps

  1. Take the next code point.
  2. UTF-8: pick 1, 2, 3 or 4 bytes by range and spread the bits into the payload positions of the lead and continuation bytes.
  3. UTF-16: below U+10000 write it as one unit; otherwise subtract 0x10000 and split the 20 bits into a high and a low surrogate.

Invariants

What holds at every step; the correctness argument rests on these.

  • Every valid code point has exactly one encoding in each form.
  • Continuation bytes always start with the bits 10, so a decoder can resynchronize.

Complexity

UTF-8 and UTF-16 encoding complexity
CaseTimeExtra spaceNotes
Encode n code pointsO(n)O(n) outputAt most 4 bytes or 2 units per code point.

When to use it

Use it when

  • You index, slice or measure strings across languages, files or network protocols.

Avoid it when

  • Hand-rolled encoders in production: use the standard library (Encoding.UTF8, str.encode, StandardCharsets) or, in C++, a vetted library.

Step through it

The interactive lab for utf-8 and utf-16 encoding: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

The hand-written UTF-8 and UTF-16 encoders in four languages, each checked against one shared fixture (every length boundary, surrogate-adjacent values, U+10FFFF, combining marks, flags, ZWJ sequences) and 5,000 random scalar values compared with the built-in encoders (C#, Python, Java) or with independent decoders and u8/u literals (C++); surrogates and out-of-range values are rejected.

namespace Bekadan.Dsa.Examples.Strings;
 
/// <summary>
/// UTF-8 and UTF-16 encoders written out by hand, to show where the bytes and
/// code units of a .NET string come from. Production code uses
/// <see cref="System.Text.Encoding.UTF8"/> and <see cref="System.Text.Rune"/>.
/// </summary>
public static class TextEncoding
{
    /// <summary>The 1–4 UTF-8 bytes of one Unicode scalar value.</summary>
    public static byte[] Utf8Bytes(int codePoint)
    {
        CheckScalar(codePoint);
        if (codePoint < 0x80)
            return [(byte)codePoint];                                  // 0xxxxxxx
        if (codePoint < 0x800)
            return [(byte)(0xC0 | (codePoint >> 6)),                   // 110xxxxx
                    (byte)(0x80 | (codePoint & 0x3F))];                // 10xxxxxx
        if (codePoint < 0x10000)
            return [(byte)(0xE0 | (codePoint >> 12)),                  // 1110xxxx
                    (byte)(0x80 | ((codePoint >> 6) & 0x3F)),
                    (byte)(0x80 | (codePoint & 0x3F))];
        return [(byte)(0xF0 | (codePoint >> 18)),                      // 11110xxx
                (byte)(0x80 | ((codePoint >> 12) & 0x3F)),
                (byte)(0x80 | ((codePoint >> 6) & 0x3F)),
                (byte)(0x80 | (codePoint & 0x3F))];
    }
 
    /// <summary>The one or two UTF-16 code units (a .NET <c>char</c> is one unit) of a scalar value.</summary>
    public static char[] Utf16Units(int codePoint)
    {
        CheckScalar(codePoint);
        if (codePoint < 0x10000)
            return [(char)codePoint];
        int v = codePoint - 0x10000;                 // 20 bits
        return [(char)(0xD800 + (v >> 10)),          // high surrogate: top 10 bits
                (char)(0xDC00 + (v & 0x3FF))];       // low surrogate: bottom 10 bits
    }
 
    /// <summary>Encodes a sequence of scalar values both ways.</summary>
    public static (byte[] Utf8, char[] Utf16) Encode(IEnumerable<int> codePoints)
    {
        var utf8 = new List<byte>();
        var utf16 = new List<char>();
        foreach (int codePoint in codePoints)
        {
            utf8.AddRange(Utf8Bytes(codePoint));
            utf16.AddRange(Utf16Units(codePoint));
        }
        return (utf8.ToArray(), utf16.ToArray());
    }
 
    /// <summary>
    /// The code points of a .NET string: a high surrogate followed by a low one is
    /// one code point. Throws on a lone surrogate (strings may contain them).
    /// </summary>
    public static List<int> CodePoints(string text)
    {
        var result = new List<int>();
        for (int i = 0; i < text.Length; i++)
        {
            char unit = text[i];
            if (char.IsHighSurrogate(unit) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
                result.Add(0x10000 + ((unit - 0xD800) << 10) + (text[++i] - 0xDC00));
            else if (char.IsSurrogate(unit))
                throw new ArgumentException($"Lone surrogate at index {i}.", nameof(text));
            else
                result.Add(unit);
        }
        return result;
    }
 
    private static void CheckScalar(int codePoint)
    {
        if (codePoint is < 0 or > 0x10FFFF or (>= 0xD800 and <= 0xDFFF))
            throw new ArgumentOutOfRangeException(nameof(codePoint), "Not a Unicode scalar value.");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Strings/TextEncoding.cs

"""UTF-8 and UTF-16 encoders written out by hand.
 
A Python str is a sequence of code points, so ord(ch) already gives the value
to encode. Production code uses str.encode("utf-8") / str.encode("utf-16-le").
"""
 
from collections.abc import Iterable
 
 
def _check_scalar(code_point: int) -> None:
    # Python strings may hold lone surrogates ("\ud800"); they are not encodable.
    if not 0 <= code_point <= 0x10FFFF or 0xD800 <= code_point <= 0xDFFF:
        raise ValueError(f"not a Unicode scalar value: {code_point:#x}")
 
 
def utf8_bytes(code_point: int) -> bytes:
    """The 1-4 UTF-8 bytes of one Unicode scalar value."""
    _check_scalar(code_point)
    if code_point < 0x80:
        return bytes([code_point])  # 0xxxxxxx
    if code_point < 0x800:
        return bytes([0xC0 | (code_point >> 6),  # 110xxxxx
                      0x80 | (code_point & 0x3F)])  # 10xxxxxx
    if code_point < 0x10000:
        return bytes([0xE0 | (code_point >> 12),  # 1110xxxx
                      0x80 | ((code_point >> 6) & 0x3F),
                      0x80 | (code_point & 0x3F)])
    return bytes([0xF0 | (code_point >> 18),  # 11110xxx
                  0x80 | ((code_point >> 12) & 0x3F),
                  0x80 | ((code_point >> 6) & 0x3F),
                  0x80 | (code_point & 0x3F)])
 
 
def utf16_units(code_point: int) -> list[int]:
    """The one or two 16-bit UTF-16 code units of a scalar value."""
    _check_scalar(code_point)
    if code_point < 0x10000:
        return [code_point]
    v = code_point - 0x10000  # 20 bits
    return [0xD800 + (v >> 10),  # high surrogate: top 10 bits
            0xDC00 + (v & 0x3FF)]  # low surrogate: bottom 10 bits
 
 
def encode(code_points: Iterable[int]) -> tuple[bytes, list[int]]:
    """Encodes a sequence of scalar values both ways."""
    utf8 = bytearray()
    utf16: list[int] = []
    for code_point in code_points:
        utf8 += utf8_bytes(code_point)
        utf16 += utf16_units(code_point)
    return bytes(utf8), utf16

Tested on CPython 3.14.0 · examples/python/dsa_examples/text_encoding.py

package dev.bekadan.dsa.strings;
 
import java.io.ByteArrayOutputStream;
 
/**
 * UTF-8 and UTF-16 encoders written out by hand, to show where the bytes and
 * the {@code char}s of a Java String come from. Production code uses
 * {@code String.getBytes(StandardCharsets.UTF_8)} and {@code Character.toChars}.
 */
public final class TextEncoding {
    private TextEncoding() {
    }
 
    /** The 1-4 UTF-8 bytes of one Unicode scalar value. Java bytes are signed; the bits are what matter. */
    public static byte[] utf8Bytes(int codePoint) {
        checkScalar(codePoint);
        if (codePoint < 0x80) {
            return new byte[] {(byte) codePoint};                        // 0xxxxxxx
        }
        if (codePoint < 0x800) {
            return new byte[] {(byte) (0xC0 | (codePoint >> 6)),         // 110xxxxx
                               (byte) (0x80 | (codePoint & 0x3F))};      // 10xxxxxx
        }
        if (codePoint < 0x10000) {
            return new byte[] {(byte) (0xE0 | (codePoint >> 12)),        // 1110xxxx
                               (byte) (0x80 | ((codePoint >> 6) & 0x3F)),
                               (byte) (0x80 | (codePoint & 0x3F))};
        }
        return new byte[] {(byte) (0xF0 | (codePoint >> 18)),            // 11110xxx
                           (byte) (0x80 | ((codePoint >> 12) & 0x3F)),
                           (byte) (0x80 | ((codePoint >> 6) & 0x3F)),
                           (byte) (0x80 | (codePoint & 0x3F))};
    }
 
    /** The one or two UTF-16 code units (a Java {@code char} is one unit) of a scalar value. */
    public static char[] utf16Units(int codePoint) {
        checkScalar(codePoint);
        if (codePoint < 0x10000) {
            return new char[] {(char) codePoint};
        }
        int v = codePoint - 0x10000;                  // 20 bits
        return new char[] {(char) (0xD800 + (v >> 10)),   // high surrogate: top 10 bits
                           (char) (0xDC00 + (v & 0x3FF))}; // low surrogate: bottom 10 bits
    }
 
    /** Both encodings of a sequence of scalar values. */
    public record Encoded(byte[] utf8, char[] utf16) {
    }
 
    public static Encoded encode(int[] codePoints) {
        ByteArrayOutputStream utf8 = new ByteArrayOutputStream();
        StringBuilder utf16 = new StringBuilder();
        for (int codePoint : codePoints) {
            utf8.writeBytes(utf8Bytes(codePoint));
            utf16.append(utf16Units(codePoint));
        }
        return new Encoded(utf8.toByteArray(), utf16.toString().toCharArray());
    }
 
    /**
     * The code points of a Java String: a high surrogate followed by a low one is
     * one code point. Throws on a lone surrogate (Strings may contain them).
     */
    public static int[] codePoints(String text) {
        int[] result = new int[text.length()];
        int count = 0;
        for (int i = 0; i < text.length(); i++) {
            char unit = text.charAt(i);
            if (Character.isHighSurrogate(unit) && i + 1 < text.length() && Character.isLowSurrogate(text.charAt(i + 1))) {
                result[count++] = 0x10000 + ((unit - 0xD800) << 10) + (text.charAt(++i) - 0xDC00);
            } else if (Character.isSurrogate(unit)) {
                throw new IllegalArgumentException("lone surrogate at index " + i);
            } else {
                result[count++] = unit;
            }
        }
        return java.util.Arrays.copyOf(result, count);
    }
 
    private static void checkScalar(int codePoint) {
        if (codePoint < 0 || codePoint > 0x10FFFF || (codePoint >= 0xD800 && codePoint <= 0xDFFF)) {
            throw new IllegalArgumentException("not a Unicode scalar value: " + Integer.toHexString(codePoint));
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/strings/TextEncoding.java

#pragma once
 
#include <cstdint>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
 
namespace bekadan::dsa {
 
// UTF-8 and UTF-16 encoders written out by hand. C++ has no standard
// converter (std::codecvt_utf8 was deprecated in C++17 and removed in C++26),
// so code like this, or a library such as ICU, is what real programs use.
// A std::string is a sequence of bytes; it does not know about encodings.
 
inline void check_scalar(char32_t code_point) {
    if (code_point > 0x10FFFF || (code_point >= 0xD800 && code_point <= 0xDFFF))
        throw std::invalid_argument("not a Unicode scalar value");
}
 
// The 1-4 UTF-8 bytes of one Unicode scalar value.
inline std::vector<std::uint8_t> utf8_bytes(char32_t code_point) {
    check_scalar(code_point);
    const auto byte = [](char32_t bits) { return static_cast<std::uint8_t>(bits); };
    if (code_point < 0x80)
        return {byte(code_point)};                               // 0xxxxxxx
    if (code_point < 0x800)
        return {byte(0xC0 | (code_point >> 6)),                  // 110xxxxx
                byte(0x80 | (code_point & 0x3F))};               // 10xxxxxx
    if (code_point < 0x10000)
        return {byte(0xE0 | (code_point >> 12)),                 // 1110xxxx
                byte(0x80 | ((code_point >> 6) & 0x3F)),
                byte(0x80 | (code_point & 0x3F))};
    return {byte(0xF0 | (code_point >> 18)),                     // 11110xxx
            byte(0x80 | ((code_point >> 12) & 0x3F)),
            byte(0x80 | ((code_point >> 6) & 0x3F)),
            byte(0x80 | (code_point & 0x3F))};
}
 
// The one or two UTF-16 code units of a scalar value.
inline std::u16string utf16_units(char32_t code_point) {
    check_scalar(code_point);
    if (code_point < 0x10000)
        return std::u16string(1, static_cast<char16_t>(code_point));
    const char32_t v = code_point - 0x10000;                        // 20 bits
    return {static_cast<char16_t>(0xD800 + (v >> 10)),              // high surrogate: top 10 bits
            static_cast<char16_t>(0xDC00 + (v & 0x3FF))};           // low surrogate: bottom 10 bits
}
 
struct Encoded {
    std::vector<std::uint8_t> utf8;
    std::u16string utf16;
};
 
// Encodes a sequence of scalar values (a std::u32string holds one per element) both ways.
inline Encoded encode(std::u32string_view code_points) {
    Encoded out;
    for (const char32_t code_point : code_points) {
        const auto bytes = utf8_bytes(code_point);
        out.utf8.insert(out.utf8.end(), bytes.begin(), bytes.end());
        out.utf16 += utf16_units(code_point);
    }
    return out;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/text_encoding.hpp

Learn more

Data structures it uses

References