M06 · Strings

Strings in Memory: Code Units, Code Points and Graphemes

A string is a sequence of numbers plus an agreement on what they mean. This lesson encodes code points into UTF-8 and UTF-16 by hand, explains surrogate pairs and grapheme clusters, compares what C#, Java, Python and C++ store and count, and covers immutability and string builders.

~45 minBeginnerC# · Python · Java · C++
Curriculum: M06 Strings · 3 of 3 lessons available

You will be able to

  • Tell code units, code points and grapheme clusters apart, and say which one a length or an index counts in C#, Java, Python and C++.
  • Encode a code point into UTF-8 bytes and UTF-16 code units by hand, including a surrogate pair.
  • Explain why indexing a UTF-8 or UTF-16 string by "character" is not O(1).
  • Explain why strings are immutable in C#, Java and Python, and why repeated concatenation in a loop is quadratic.
  • Pick the right tool to build a string: StringBuilder, list + join, or std::string::append.

Helpful before this lesson

  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.
  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A computer cannot store "the letter é". It stores numbers, and every program that reads them has to agree on what the numbers mean. Three layers sit on top of each other:

Layer What it is Example for "é" (precomposed)
Grapheme cluster What a reader sees as one character é
Code point A number from the Unicode catalogue, U+0000 … U+10FFFF U+00E9
Code unit The fixed-size piece an encoding stores: 8 bits (UTF-8), 16 bits (UTF-16), 32 bits (UTF-32) UTF-8: C3 A9; UTF-16: 00E9

Usually one grapheme is one code point, and in ASCII text one code point is one byte, so the layers blur together. They come apart as soon as text leaves English: "é" can also be written as e + U+0301 COMBINING ACUTE ACCENT (two code points, one grapheme), an emoji like 😀 (U+1F600) is one code point but two UTF-16 units and four UTF-8 bytes, and a flag 🇹🇷 is two code points that render as one symbol.

Encoding a code point

The lab encodes a string one code point at a time and shows which branch of each encoder runs.

UTF-8: 1 to 4 bytes

UTF-8 splits the code point's bits over a lead byte and continuation bytes. The lead byte says how many bytes follow; every continuation byte starts with 10.

Code point range Bytes Bit layout
U+0000 – U+007F 1 0xxxxxxx
U+0080 – U+07FF 2 110xxxxx 10xxxxxx
U+0800 – U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
U+10000 – U+10FFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
utf8(cp):
    if cp < 0x80:    return [cp]
    if cp < 0x800:   return [0xC0 | cp >> 6, 0x80 | cp & 0x3F]
    if cp < 0x10000: return [0xE0 | cp >> 12, 0x80 | (cp >> 6) & 0x3F, 0x80 | cp & 0x3F]
    return [0xF0 | cp >> 18, 0x80 | (cp >> 12) & 0x3F, 0x80 | (cp >> 6) & 0x3F, 0x80 | cp & 0x3F]

Worked example: € is U+20AC = 0010 0000 1010 1100 (16 bits), so it takes three bytes. The bits go 0010 | 000010 | 101100 into 1110xxxx 10xxxxxx 10xxxxxx: 11100010 10000010 10101100 = E2 82 AC. Press One of each in the lab and step to the € to see the same split.

Three properties make UTF-8 the default for files and networks:

  • ASCII compatible. Every ASCII file is already valid UTF-8, byte for byte.
  • Self-synchronising. Continuation bytes (10xxxxxx) can never be mistaken for a lead byte, so a reader can find the start of a character from any position, and a byte-level search for a valid UTF-8 pattern can only match at character boundaries.
  • No byte-order question. The unit is a byte, so there is no big-endian/little-endian variant.

UTF-16: one unit or a surrogate pair

Code points up to U+FFFF (the Basic Multilingual Plane) fit in one 16-bit unit. Larger ones are split into a surrogate pair: subtract 0x10000 to get a 20-bit number, put the top 10 bits into a high surrogate (0xD800 + …) and the bottom 10 into a low surrogate (0xDC00 + …).

utf16(cp):
    if cp < 0x10000: return [cp]
    v = cp - 0x10000                       # 20 bits
    return [0xD800 + (v >> 10), 0xDC00 + (v & 0x3FF)]

😀 = U+1F600: v = 0xF600 = 0000 1111 0110 0000 0000; the top ten bits are 0x3D and the bottom ten 0x200, giving D83D DE00. The range U+D800–U+DFFF is reserved for these halves, which is why those numbers are not valid code points on their own (the encoders in all four listings reject them). A UTF-16 string that contains half a pair, a lone surrogate, cannot be converted to UTF-8.

Same text, different sizes

Text Code points UTF-8 bytes UTF-16 units
Hello 5 5 5
Aé€😀 4 10 5
中文 2 6 2
🇹🇷 2 8 4

UTF-8 is compact for Latin text; UTF-16 can be smaller for East Asian text. Neither is "one unit per character".

Grapheme clusters

A grapheme cluster is a user-perceived character: e + combining accent, a flag (two regional-indicator code points), or an emoji family joined by U+200D ZERO WIDTH JOINER. The rules for where one cluster ends are in Unicode Standard Annex #29 and change with new Unicode versions.

This is why the visualizer stops at code points. C# has StringInfo (text elements follow grapheme rules since .NET 5), Java's BreakIterator.getCharacterInstance() approximates them, Python's standard library has no cluster API (the third-party regex module has \X), and standard C++ has none. A correct cross-language visualizer of clusters would need its own copy of the segmentation data, so the lab shows the code points a cluster is made of instead; the é two ways and ZWJ sequence presets make the difference visible.

What it means in practice: reversing a string, truncating it to "n characters" or moving a cursor should work on grapheme clusters, or the user sees broken accents and half flags.

What each language stores and counts

C# string Java String Python str C++ std::string
Element type char = UTF-16 code unit char = UTF-16 code unit code point char = byte (no encoding attached)
Length / length() / len / size() of 😀 2 2 1 4 if it holds UTF-8
Code points EnumerateRunes(), Rune codePoints(), codePointAt iterate the str decode yourself or use a library
Can hold a lone surrogate yes yes yes ("\ud800"), but encode refuses n/a
  • C# and Java strings are arrays of UTF-16 code units. s[i] / s.charAt(i) is O(1) but may return half of a surrogate pair. Java stores Latin-1-only strings in one byte per character internally (compact strings), but the API still speaks UTF-16.
  • Python 3 str is a sequence of code points, so len and indexing count code points, and both are O(1). CPython makes that possible by storing each string with a fixed width of 1, 2 or 4 bytes per code point, chosen by the widest character in it (PEP 393). bytes is a separate type.
  • C++ std::string is a byte container. It works fine for UTF-8 text as long as you remember that size() counts bytes and s[i] is a byte. std::u8string, std::u16string and std::u32string label the encoding in the type but add no Unicode operations.

Indexing by character is not O(1) in UTF-8 or UTF-16: to find the k-th code point you must scan from the start, because earlier characters may take more than one unit. Only fixed-width forms (UTF-32, CPython's internal layout) give O(1) code point indexing; nothing gives O(1) grapheme indexing.

Immutability and building strings

In C#, Java and Python a string object never changes after it is created. Benefits: strings can be shared between threads and data structures without copying, used safely as hash keys (the hash can be cached), and passed around without defensive copies. The cost: every "modification" creates a new string.

So this loop is quadratic:

s = ""
for each of n pieces:
    s = s + piece        # copies everything built so far

The i-th concatenation copies about i pieces, so the total is 1 + 2 + … + n ≈ n²/2 copies. The fix is a growable buffer, the dynamic array from the arrays module, with amortised O(1) append:

Language Build a string from many pieces Notes
C# var sb = new StringBuilder(); sb.Append(piece); sb.ToString() string.Join / string.Concat for a known sequence
Java var sb = new StringBuilder(); sb.append(piece); sb.toString() String.join; the compiler already uses a builder for a + b + c in one expression, not across loop iterations
Python parts.append(piece) then "".join(parts) CPython sometimes optimises s += piece in place, but that is an implementation detail, not a guarantee
C++ s += piece or s.append(piece) std::string is mutable and grows like std::vector; call reserve if you know the size

In C++ the question is reversed: std::string is mutable and copied by value, so pass const std::string& or std::string_view to avoid copies.

Comparison and equality

  • Ordinal comparison compares code units (C#, Java), code points (Python) or bytes (C++). It is fast and predictable, and it is what hashing and the string-matching lesson use. Note that UTF-16 ordinal order differs from code point order above U+FFFF, because surrogates (D800–DFFF) sort below U+E000–U+FFFF.
  • Culture-aware comparison (C# StringComparison.CurrentCulture, Java Collator, ICU) sorts the way people expect in a language, for example "ä" next to "a" in German.
  • Normalisation. Precomposed é (U+00E9) and e + U+0301 compare unequal ordinally. Normalise both sides first (NFC or NFD) when the text comes from different sources: string.Normalize(), java.text.Normalizer, unicodedata.normalize, or ICU in C++.

The teaching implementation

Utf8Bytes / utf8_bytes and Utf16Units / utf16_units are written the same way in all four languages. Each language reads one shared fixture (every length boundary, U+D7FF and U+E000 around the surrogate block, U+FFFF, U+10000, U+10FFFF, combining marks, a flag, a ZWJ sequence) and checks 5,000 random code points against its built-in encoder: Encoding.UTF8 and char.ConvertFromUtf32 in C#, str.encode in Python, getBytes(UTF_8) and Character.toChars in Java. Standard C++ has no UTF-8 converter any more (std::codecvt_utf8 was deprecated in C++17 and removed in C++26), so the C++ test round-trips through independent decoders and compares with u8"…" and u"…" literals.

Common mistakes

  • Using Length as "number of characters" for user-facing limits. An emoji counts 2 in C# and Java, 1 in Python and 4 in a UTF-8 std::string.
  • Cutting a string at an arbitrary index. In UTF-16 you can split a surrogate pair; in UTF-8 you can split a multi-byte sequence; in any encoding you can split a grapheme cluster.
  • Reversing code units. Reversing D83D DE00 gives DE00 D83D, which is invalid.
  • Assuming one byte per character when sizing buffers for UTF-8: allow up to 4 bytes per code point (3 per UTF-16 unit).
  • Concatenating in a loop with + in C#, Java or Python.
  • Comparing user input without normalising it.

Edge cases

  • The empty string: zero code points, zero bytes, zero units.
  • U+0000 is a valid code point (one byte 00); C APIs that use NUL-terminated strings cannot hold it.
  • Code points just below and above the surrogate range (U+D7FF, U+E000) are ordinary 3-byte characters.
  • U+10FFFF is the largest code point: F4 8F BF BF in UTF-8, DBFF DFFF in UTF-16.

Worked practice

1. How many UTF-8 bytes and UTF-16 units does "naïve" take?

Answer

Five code points: n, a, ï (U+00EF), v, e. UTF-8: 1 + 1 + 2 + 1 + 1 = 6 bytes. UTF-16: 5 units, if ï is precomposed. Written as i + U+0308 it is six code points, 7 bytes and 6 units.

2. Encode U+00E9 in UTF-8.

Answer

0xE9 = 000 1110 1001 (11 bits): 00011 | 101001 into 110xxxxx 10xxxxxx gives 11000011 10101001 = C3 A9.

3. A C# method truncates a username to name.Substring(0, 10). What can go wrong?

Answer

If the 10th and 11th units form a surrogate pair, the result ends with a lone high surrogate, which is not valid Unicode and fails when encoded to UTF-8 (or prints as a replacement character). It can also cut a grapheme cluster in half. Truncate on text-element boundaries (StringInfo) instead.

4. Why is "".join(parts) linear but repeated s = s + p quadratic?

Answer

join first adds up the lengths, allocates the result once and copies each piece once. Repeated + allocates a new string every time and copies everything built so far, 1 + 2 + … + n pieces.

Summary

  • Code unit, code point and grapheme cluster are different things; ASCII hides the difference.
  • UTF-8 uses 1–4 bytes per code point and is ASCII compatible; UTF-16 uses one or two 16-bit units, with surrogate pairs above U+FFFF.
  • C# and Java count UTF-16 units, Python counts code points, C++ std::string counts bytes. None of them counts grapheme clusters by default.
  • Strings are immutable in C#, Java and Python: build them with a builder or join, not + in a loop.

Full implementation

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

References