Strings · O(n) in code points
UTF-8 and UTF-16 encoding
Code points become 1–4 UTF-8 bytes and 1–2 UTF-16 units, including surrogate pairs.
The full explanation, derivation and practice are in the lesson Strings in memory: code units, code points and graphemes.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
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