Programming Search⌘K

Formatcore

UTF-8

Also called FSS-UTF, UTF-2.

UTF-8 is the encoding that writes each Unicode scalar value as a sequence of one to four bytes. The bytes 00 to 7F are the same as ASCII, and no byte of a longer sequence is in that range.

What it is

UTF-8 is a character encoding. It writes each Unicode scalar value as a sequence of one to four bytes.2 A scalar value is a code point in the range U+0000 to U+10FFFF, other than a surrogate code point (U+D800 to U+DFFF). The Unicode Standard defines UTF-8, and RFC 3629 of the IETF defines the same encoding for the protocols of the Internet.1

The encoding has a small set of properties, and most of its uses follow from them:1

  • The code points U+0000 to U+007F are one byte each, with the same values as ASCII. So each ASCII text is also a UTF-8 text.
  • The bytes 00 to 7F never occur inside a longer sequence. A program that looks only for ASCII bytes, such as /, , or the newline, can process UTF-8 text without decoding it.
  • The first byte of a sequence gives the length of the sequence. The other bytes have a fixed bit pattern, so a reader can find the start of a character from any position in the stream.
  • The bytes C0, C1 and F5 to FF never occur.
  • The byte order of two UTF-8 strings is the same as the order of their code points.

A program that handles text uses three different units, and UTF-8 makes the difference between them visible. A byte is a code unit of UTF-8. A code point is the number of one character in Unicode. A grapheme cluster is what a reader sees as one character.12 The letter "é" can be one code point (U+00E9) or two (U+0065 U+0301). The flag of Vietnam is two code points and eight bytes. A string has a different length in each unit, and each language counts a different unit by default (see Examples).

History

Rob Pike and Ken Thompson needed an encoding for the Plan 9 operating system in 1992. They first used the original UTF of ISO 10646. That encoding was not self-synchronizing: a reader could not find the character boundaries without a read from the start of the string. It also needed multiplication, division and modulo to encode and decode.5 In August 1992, X/Open circulated a proposal for a byte encoding that was safe for file names.5

Pike tells the rest in an e-mail of 2003. Some members of an X/Open committee asked Pike and Thompson to check their design, FSS/UTF. That design could not resynchronize a byte stream that a reader picked up in the middle. Thompson designed a new bit packing "on a placemat in a New Jersey diner one night in September or so 1992". He wrote the code that night, and by the Friday Plan 9 ran only on the new encoding.6 The Plan 9 mail archive has the proposal that Thompson sent to X/Open on Tuesday 8 September 1992.6 The paper of Pike and Thompson at the Winter 1993 USENIX Conference says that their proposal, "originally known informally as UTF-2 and FSS-UTF, is now referred to as UTF-8", and that ISO approved it to become Annex P to ISO 10646.5

RFC 2044 (October 1996, Informational) and RFC 2279 (January 1998, Standards Track) defined UTF-8 for the Internet.87 RFC 2279 says that UTF-8 was a project of the X/Open Joint Internationalization Group, with Gary Miller, Greger Leijonhufvud and John Entenmann as the original authors, and that Thompson and Pike "did significant work for the formal UTF-8".7 Pike wrote in 2003 that this story "originates in RFC2279" and is not correct.6 RFC 3629 of November 2003 says that Thompson devised UTF-8, "guided by design criteria specified by Rob Pike".1

Syntax or structure

Table 3-6 of the Unicode Standard and Section 3 of RFC 3629 give the bit layout. The letter x marks a bit of the code point.21

Code points           Byte 1    Byte 2    Byte 3    Byte 4    Bits
U+0000  ..U+007F      0xxxxxxx                                  7
U+0080  ..U+07FF      110xxxxx  10xxxxxx                       11
U+0800  ..U+FFFF      1110xxxx  10xxxxxx  10xxxxxx             16
U+10000 ..U+10FFFF    11110xxx  10xxxxxx  10xxxxxx  10xxxxxx   21

The number of leading 1 bits in the first byte is the length of the sequence. A first byte that starts with 0 is a sequence of one byte. Each continuation byte starts with the bits 10, so it is in the range 80 to BF. A reader that starts in the middle of a stream skips the continuation bytes and finds the next first byte. A program needs to search at most four bytes back to find the start of a character.3

The layout alone allows more than one sequence for some code points. The bytes C0 AF fit the pattern of two bytes and hold the value 2F, the code of /. The bytes ED A0 80 fit the pattern of three bytes and hold the surrogate D800. These sequences are ill-formed. Table 3-7 of the Unicode Standard lists the only well-formed sequences, and RFC 3629 gives the same rules in ABNF.21

UTF8-octets = *( UTF8-char )
UTF8-char   = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
UTF8-1      = %x00-7F
UTF8-2      = %xC2-DF UTF8-tail
UTF8-3      = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
              %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
UTF8-4      = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
              %xF4 %x80-8F 2( UTF8-tail )
UTF8-tail   = %x80-BF

Each rule closes one gap of the bit layout:

  • Overlong forms. A sequence that is longer than necessary is ill-formed. The first byte C0 or C1 can only start an overlong form of two bytes, so these two bytes never occur. After E0, the second byte must be A0 or more. After F0, it must be 90 or more. So the shortest form is the only form.
  • Surrogates. The code points U+D800 to U+DFFF are not scalar values. UTF-16 uses them in pairs for the code points above U+FFFF.2 After ED, the second byte must be 9F or less, so UTF-8 cannot encode a surrogate.
  • The upper limit. After F4, the second byte must be 8F or less. The first bytes F5 to FF are not used. So the largest value is U+10FFFF, the largest code point that UTF-16 can reach.1

These checks matter for security. A decoder that accepts an overlong form lets a forbidden byte pass a filter in a different form. RFC 3629 gives the example of a parser that rejects the bytes 2F 2E 2E 2F ("/../") but accepts 2F C0 AE 2E 2F and reads it as the same path. It says that a virus used this attack against web servers in 2001.1 So RFC 3629 says that a decoder MUST protect against the decode of invalid sequences.1

The byte order mark

The character U+FEFF has the formal name ZERO WIDTH NO-BREAK SPACE, and the informal name byte order mark (BOM). In UTF-8 it is the bytes EF BB BF.1 UTF-8 has one byte as its code unit, so it has no byte order.1 At the start of a text, the bytes EF BB BF are a strong sign that the text is UTF-8. The Unicode Standard does not require a BOM in UTF-8, and a BOM does not make a text non-conformant.2 RFC 3629 says that U+FEFF anywhere other than at the start of a stream MUST be read as a zero width no-break space. It says that a protocol SHOULD forbid the mark when the protocol always uses UTF-8.1 A program that reads the bytes EF BB BF with the code page Windows-1252 shows them as "".4

Ill-formed input and U+FFFD

A decoder that finds an ill-formed sequence can stop with an error, or it can put U+FFFD REPLACEMENT CHARACTER in place of the bad bytes. The Unicode Standard requires only that the decoder does not consume a well-formed sequence as part of the error. It describes a practice for the number of U+FFFD characters, the "substitution of maximal subparts". The practice is not required for conformance.2 A maximal subpart is the longest start of a sequence that can still be well-formed. Each maximal subpart becomes one U+FFFD, and each byte that cannot start a sequence becomes one U+FFFD. The Unicode Standard says that this practice is the one of the W3C encoding standard, the WHATWG Encoding Standard.210

Examples

The function encode below follows Table 3-6. It checks the result against the codec of Python for one character of each length.13

def encode(code_point):
    if code_point < 0x80:
        return bytes([code_point])
    if code_point < 0x800:
        return bytes([0xC0 | code_point >> 6, 0x80 | code_point & 0x3F])
    if code_point < 0x10000:
        if 0xD800 <= code_point <= 0xDFFF:
            raise ValueError(f"U+{code_point:04X} is a surrogate")
        return bytes([0xE0 | code_point >> 12, 0x80 | code_point >> 6 & 0x3F, 0x80 | code_point & 0x3F])
    if code_point <= 0x10FFFF:
        return bytes([0xF0 | code_point >> 18, 0x80 | code_point >> 12 & 0x3F, 0x80 | code_point >> 6 & 0x3F, 0x80 | code_point & 0x3F])
    raise ValueError(f"U+{code_point:X} is above U+10FFFF")


for code_point in 0x41, 0xE9, 0x20AC, 0x1D11E:
    data = encode(code_point)
    assert data == chr(code_point).encode("utf-8")
    bits = " ".join(f"{byte:08b}" for byte in data)
    print(f"U+{code_point:04X} {len(data)} {data.hex(' ').upper():11} {bits}")

for code_point in 0xDC00, 0x110000:
    try:
        encode(code_point)
    except ValueError as error:
        print(error)
Output
U+0041 1 41          01000001
U+00E9 2 C3 A9       11000011 10101001
U+20AC 3 E2 82 AC    11100010 10000010 10101100
U+1D11E 4 F0 9D 84 9E 11110000 10011101 10000100 10011110
U+DC00 is a surrogate
U+110000 is above U+10FFFF

The rules of Table 3-7 form a regular language, so a regular expression over bytes can check UTF-8. The pattern below has one branch for each row of the table. It agrees with the strict decoder of Python on each sample. The samples E0 9F 80 and F4 80 83 92 are the examples of the Unicode Standard.2

import re

WELL_FORMED = re.compile(
    rb"""(?:
      [\x00-\x7F]
    | [\xC2-\xDF][\x80-\xBF]
    | \xE0[\xA0-\xBF][\x80-\xBF]
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
    | \xED[\x80-\x9F][\x80-\xBF]
    | \xF0[\x90-\xBF][\x80-\xBF]{2}
    | [\xF1-\xF3][\x80-\xBF]{3}
    | \xF4[\x80-\x8F][\x80-\xBF]{2}
    )*""",
    re.VERBOSE,
)

samples = [b"h\xc3\xa9\xe2\x82\xac", b"\xc0\xaf", b"\xe0\x9f\x80", b"\xed\xa0\x80", b"\xf4\x80\x83\x92", b"\xf4\x90\x80\x80"]
for data in samples:
    matched = WELL_FORMED.fullmatch(data) is not None
    try:
        data.decode("utf-8")
        decoded = True
    except UnicodeDecodeError:
        decoded = False
    print(f"{data.hex(' '):17} {matched} {decoded}")
Output
68 c3 a9 e2 82 ac True True
c0 af             False False
e0 9f 80          False False
ed a0 80          False False
f4 80 83 92       True True
f4 90 80 80       False False

The strict mode of the Python codec raises UnicodeDecodeError for ill-formed input. The error handler replace puts U+FFFD in place of the bad bytes.13 The count of U+FFFD shows the maximal subparts. The surrogate ED A0 80 gives three, because no well-formed sequence starts with ED A0. The truncated E2 82 gives one, because it is the start of a well-formed sequence.

samples = {
    "overlong /": b"\xc0\xaf",
    "overlong NUL": b"\xc0\x80",
    "surrogate": b"\xed\xa0\x80",
    "above 10FFFF": b"\xf4\x90\x80\x80",
    "truncated": b"\xe2\x82",
    "lone tail": b"\x80",
}
for name, data in samples.items():
    try:
        data.decode("utf-8")
    except UnicodeDecodeError as error:
        replaced = data.decode("utf-8", errors="replace")
        print(f"{name:13} {data.hex(' '):12} {replaced.count(chr(0xFFFD))} x U+FFFD  {error.reason}")
Output
overlong /    c0 af        2 x U+FFFD  invalid start byte
overlong NUL  c0 80        2 x U+FFFD  invalid start byte
surrogate     ed a0 80     3 x U+FFFD  invalid continuation byte
above 10FFFF  f4 90 80 80  4 x U+FFFD  invalid continuation byte
truncated     e2 82        1 x U+FFFD  unexpected end of data
lone tail     80           1 x U+FFFD  invalid start byte

A Python str is a sequence of code points, so len counts code points. The example counts the same strings in three units.

samples = {
    "e and accent": "e\u0301",
    "flag": "\U0001F1FB\U0001F1F3",
    "woman coder": "\U0001F469\u200D\U0001F4BB",
    "hangul": "\uD55C",
}
for name, text in samples.items():
    code_points = " ".join(f"U+{ord(c):04X}" for c in text)
    utf8 = len(text.encode("utf-8"))
    utf16 = len(text.encode("utf-16-le")) // 2
    print(f"{name:13} {code_points:22} bytes={utf8:2} utf16={utf16} code_points={len(text)}")
Output
e and accent  U+0065 U+0301          bytes= 3 utf16=2 code_points=2
flag          U+1F1FB U+1F1F3        bytes= 8 utf16=4 code_points=2
woman coder   U+1F469 U+200D U+1F4BB bytes=11 utf16=5 code_points=3
hangul        U+D55C                 bytes= 3 utf16=1 code_points=1

Each of these strings is one grapheme cluster. The flag is two regional indicator symbols. The woman coder is two emoji with U+200D ZERO WIDTH JOINER between them. The example files for JavaScript, Java and C# count the grapheme clusters too.

Two strings can look the same and differ in their code points, so their bytes differ too. UTF-8 does not change this: it gives one byte sequence for each sequence of code points.1 Normalization maps equivalent strings to one form. NFC composes and NFD decomposes. NFKC and NFKD also replace compatibility characters, such as the ligature "fi", with their plain forms.1114

import unicodedata

composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(composed == decomposed, len(composed), len(decomposed))
print(composed.encode("utf-8").hex(" "), "|", decomposed.encode("utf-8").hex(" "))
print(unicodedata.normalize("NFC", decomposed) == composed)
print(unicodedata.normalize("NFD", composed) == decomposed)
print(unicodedata.normalize("NFKC", "\uFB01le \u2460"))
Output
False 4 5
63 61 66 c3 a9 | 63 61 66 65 cc 81
True
True
file 1

The codec utf-8 of Python keeps a leading BOM as the character U+FEFF. The codec utf-8-sig removes it on decode and writes it on encode.13

data = b"\xef\xbb\xbfid,name\n"
print(repr(data.decode("utf-8")))
print(repr(data.decode("utf-8-sig")))
print("name".encode("utf-8-sig").hex(" "))
print(data.decode("cp1252")[:3], "caf\u00e9".encode("utf-8").decode("cp1252"))
Output
'\ufeffid,name\n'
'id,name\n'
ef bb bf 6e 61 6d 65
 café
#include <cstdint>
#include <cstdio>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

struct Decoded {
    char32_t code_point;
    std::size_t length;
};

std::optional<Decoded> decode_one(std::string_view bytes) {
    auto byte = [&](std::size_t i) { return static_cast<unsigned char>(bytes[i]); };
    unsigned char lead = byte(0);
    if (lead < 0x80) return Decoded{lead, 1};
    std::size_t length = lead >= 0xC2 && lead <= 0xDF ? 2 : lead >= 0xE0 && lead <= 0xEF ? 3 : lead >= 0xF0 && lead <= 0xF4 ? 4 : 0;
    if (length == 0 || bytes.size() < length) return std::nullopt;
    char32_t value = lead & (0x7F >> length);
    for (std::size_t i = 1; i < length; ++i) {
        if ((byte(i) & 0xC0) != 0x80) return std::nullopt;
        value = value << 6 | (byte(i) & 0x3F);
    }
    static const char32_t minimum[] = {0, 0, 0x80, 0x800, 0x10000};
    if (value < minimum[length] || (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) return std::nullopt;
    return Decoded{value, length};
}

void show(std::string_view name, std::string_view bytes) {
    std::printf("%-10s %2zu bytes:", std::string(name).c_str(), bytes.size());
    while (!bytes.empty()) {
        auto result = decode_one(bytes);
        if (!result) {
            std::printf(" error at 0x%02X\n", static_cast<unsigned char>(bytes[0]));
            return;
        }
        std::printf(" U+%04X", static_cast<unsigned>(result->code_point));
        bytes.remove_prefix(result->length);
    }
    std::printf("\n");
}

int main() {
    std::u8string text = u8"h\u00E9\u20AC\U0001D11E";
    std::string bytes(text.begin(), text.end());
    std::printf("%zu %zu\n", text.size(), bytes.size());
    show("valid", bytes);
    show("overlong", "\xC0\xAF");
    show("overlong3", "\xE0\x80\xAF");
    show("surrogate", "\xED\xA0\x80");
    show("too big", "\xF4\x90\x80\x80");
    show("truncated", "a\xE2\x82");
}
Output
10 10
valid      10 bytes: U+0068 U+00E9 U+20AC U+1D11E
overlong    2 bytes: error at 0xC0
overlong3   3 bytes: error at 0xE0
surrogate   3 bytes: error at 0xED
too big     4 bytes: error at 0xF4
truncated   3 bytes: U+0061 error at 0xE2
  • Verdict: idiom. A std::string holds bytes and does not know the encoding. The type char8_t and the prefix u8 mark UTF-8 text, and std::u8string holds it. The standard library has no function that validates UTF-8 or counts its code points.
  • size counts bytes. In the example, four characters take 10 bytes.
  • The function decode_one reads one sequence. It rejects a lead byte that cannot start a sequence, a missing continuation byte, an overlong form, a surrogate and a value above U+10FFFF.
  • The facets of <codecvt>, such as std::codecvt_utf8, are deprecated in the standard ([depr.locale.stdcvt]). Libraries such as ICU and simdutf validate and convert UTF-8, and ICU also does normalization and grapheme segmentation.
JavaGitHub
import java.nio.charset.StandardCharsets;
import java.text.BreakIterator;
import java.text.Normalizer;

public class Main {
    public static void main(String[] args) {
        String text = "nai\u0308ve \uD83D\uDC69\u200D\uD83D\uDCBB";
        System.out.println("UTF-8 bytes " + text.getBytes(StandardCharsets.UTF_8).length);
        System.out.println("UTF-16 chars " + text.length());
        System.out.println("code points " + text.codePointCount(0, text.length()));

        BreakIterator graphemes = BreakIterator.getCharacterInstance();
        graphemes.setText(text);
        int count = 0;
        while (graphemes.next() != BreakIterator.DONE) {
            count++;
        }
        System.out.println("grapheme clusters " + count);

        String composed = Normalizer.normalize(text, Normalizer.Form.NFC);
        System.out.println("after NFC " + composed.length() + " " + composed.getBytes(StandardCharsets.UTF_8).length);
    }
}
Output
UTF-8 bytes 19
UTF-16 chars 12
code points 10
grapheme clusters 7
after NFC 11 18
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;

public class Main {
    public static void main(String[] args) throws IOException {
        byte[] bad = {0x61, (byte) 0xC0, (byte) 0xAF, 0x62};
        String replaced = new String(bad, StandardCharsets.UTF_8);
        System.out.println(replaced.length() + " " + replaced.chars().filter(c -> c == 0xFFFD).count());

        try {
            StandardCharsets.UTF_8.newDecoder()
                .onMalformedInput(CodingErrorAction.REPORT)
                .decode(ByteBuffer.wrap(bad));
        } catch (CharacterCodingException error) {
            System.out.println(error);
        }

        HexFormat hex = HexFormat.ofDelimiter(" ");
        String sample = "\u0000\uD834\uDD1E";
        System.out.println("UTF-8          " + hex.formatHex(sample.getBytes(StandardCharsets.UTF_8)));

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        new DataOutputStream(buffer).writeUTF(sample);
        System.out.println("modified UTF-8 " + hex.formatHex(buffer.toByteArray()));
    }
}
Output
4 2
java.nio.charset.MalformedInputException: Input length = 1
UTF-8          00 f0 9d 84 9e
modified UTF-8 00 08 c0 80 ed a0 b4 ed b4 9e
  • Verdict: stdlib. String.getBytes(StandardCharsets.UTF_8) and the constructor new String(bytes, StandardCharsets.UTF_8) convert between strings and UTF-8.
  • A Java String is a sequence of UTF-16 char values. length counts code units, and codePointCount counts code points. BreakIterator.getCharacterInstance finds the boundaries of user characters, and Normalizer does the four normalization forms.
  • The String constructor replaces bad input with U+FFFD and reports nothing. A CharsetDecoder with CodingErrorAction.REPORT throws MalformedInputException.
  • DataOutputStream.writeUTF writes modified UTF-8, not UTF-8. It starts with a two-byte length. It writes U+0000 as C0 80, and it writes a character outside the BMP as two three-byte surrogates. Class files and JNI also use this form. Do not send it to a program that expects UTF-8.
  • JEP 400 made UTF-8 the default charset of the standard Java APIs, except for console I/O. Older releases took the default from the platform, so name the charset in each call.
#include <stdio.h>
#include <string.h>

/* Returns the length of the longest valid prefix, as in Table 3-7. */
static size_t valid_up_to(const unsigned char *s, size_t n, size_t *code_points) {
    size_t i = 0;
    *code_points = 0;
    while (i < n) {
        unsigned char b = s[i];
        size_t length;
        unsigned char low = 0x80, high = 0xBF;
        if (b <= 0x7F) {
            length = 1;
        } else if (b >= 0xC2 && b <= 0xDF) {
            length = 2;
        } else if (b >= 0xE0 && b <= 0xEF) {
            length = 3;
            if (b == 0xE0) low = 0xA0;
            if (b == 0xED) high = 0x9F;
        } else if (b >= 0xF0 && b <= 0xF4) {
            length = 4;
            if (b == 0xF0) low = 0x90;
            if (b == 0xF4) high = 0x8F;
        } else {
            return i;
        }
        if (i + length > n) return i;
        for (size_t k = 1; k < length; k++) {
            unsigned char c = s[i + k];
            if (k == 1 ? (c < low || c > high) : (c < 0x80 || c > 0xBF)) return i;
        }
        i += length;
        ++*code_points;
    }
    return i;
}

int main(void) {
    const char *samples[] = {
        "h\xC3\xA9\xE2\x82\xAC\xF0\x9D\x84\x9E",
        "/\xC0\xAF",
        "\xE0\x9F\x80",
        "\xED\xA0\x80",
        "\xF4\x80\x83\x92",
        "\xF4\x90\x80\x80",
        "ok\xE2\x82",
    };
    for (size_t i = 0; i < sizeof samples / sizeof samples[0]; i++) {
        size_t n = strlen(samples[i]);
        size_t count;
        size_t valid = valid_up_to((const unsigned char *)samples[i], n, &count);
        printf("bytes %zu valid %zu code points %zu %s\n", n, valid, count, valid == n ? "ok" : "ill-formed");
    }
    return 0;
}
Output
bytes 10 valid 10 code points 4 ok
bytes 3 valid 1 code points 1 ill-formed
bytes 3 valid 0 code points 0 ill-formed
bytes 3 valid 0 code points 0 ill-formed
bytes 4 valid 4 code points 1 ok
bytes 4 valid 0 code points 0 ill-formed
bytes 4 valid 2 code points 2 ill-formed
  • Verdict: idiom. ISO C strings are arrays of char that end with a NUL byte. The standard library has no function that validates UTF-8 or counts its code points, so the program does it by hand.
  • strlen counts bytes, not characters. The first sample has four characters in 10 bytes.
  • The function valid_up_to follows Table 3-7 of the Unicode Standard. It returns the length of the longest valid prefix, like valid_up_to in Rust. The samples E0 9F 80 and F4 80 83 92 are the examples of the Unicode Standard: the first is ill-formed and the second is well-formed.
  • UTF-8 never uses the byte 00 for a character other than U+0000, so the C string functions work on UTF-8 text. They count and compare bytes, not characters.
  • The functions of <wchar.h> and <uchar.h>, such as mbrtowc, depend on the locale. Libraries such as ICU and simdutf do validation and conversion without a locale.
using System.Globalization;
using System.Text;

string text = "nai\u0308ve \U0001F469\u200D\U0001F4BB";
Console.WriteLine($"UTF-8 bytes {Encoding.UTF8.GetByteCount(text)}");
Console.WriteLine($"UTF-16 chars {text.Length}");
Console.WriteLine($"runes {text.EnumerateRunes().Count()}");
Console.WriteLine($"text elements {new StringInfo(text).LengthInTextElements}");

string composed = text.Normalize(NormalizationForm.FormC);
Console.WriteLine($"after NFC {composed.Length} {Encoding.UTF8.GetByteCount(composed)}");
Output
UTF-8 bytes 19
UTF-16 chars 12
runes 10
text elements 7
after NFC 11 18
using System.Text;

byte[] bad = { 0x61, 0xC0, 0xAF, 0xED, 0xA0, 0x80, 0x62 };
string replaced = Encoding.UTF8.GetString(bad);
Console.WriteLine($"{replaced.Length} {replaced.Count(c => c == '\uFFFD')}");

try
{
    new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(bad);
}
catch (DecoderFallbackException error)
{
    Console.WriteLine(error.GetType().Name);
}

Console.WriteLine(Convert.ToHexString(Encoding.UTF8.GetBytes("a\uD800b")));
Console.WriteLine(Convert.ToHexString(Encoding.UTF8.GetPreamble()));
Console.WriteLine(new UTF8Encoding(false).GetPreamble().Length);

byte[] withBom = { 0xEF, 0xBB, 0xBF, 0x68, 0x69 };
Console.WriteLine(Encoding.UTF8.GetString(withBom).Length);
using var reader = new StreamReader(new MemoryStream(withBom));
Console.WriteLine(reader.ReadToEnd().Length);
Output
7 5
DecoderFallbackException
61EFBFBD62
EFBBBF
0
3
2
  • Verdict: stdlib. Encoding.UTF8 in the namespace System.Text converts between strings and UTF-8 bytes.
  • A .NET string is a sequence of UTF-16 char values. Length counts code units. EnumerateRunes gives the scalar values, and StringInfo.LengthInTextElements counts grapheme clusters. string.Normalize does the four normalization forms.
  • Encoding.UTF8 replaces bad input with U+FFFD, here one for each maximal subpart. A UTF8Encoding made with throwOnInvalidBytes: true throws DecoderFallbackException.
  • Encoding.UTF8.GetPreamble returns the byte order mark EF BB BF. A UTF8Encoding made with false has an empty preamble. GetString keeps a leading byte order mark in the string. A StreamReader detects it and removes it.
JavaScriptGitHub
const text = "nai\u0308ve \u{1F469}\u200D\u{1F4BB}";

const bytes = new TextEncoder().encode(text);
console.log("UTF-8 bytes", bytes.length);
console.log("UTF-16 code units", text.length);
console.log("code points", [...text].length);

const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
const graphemes = [...segmenter.segment(text)].map((part) => part.segment);
console.log("grapheme clusters", graphemes.length);

const composed = text.normalize("NFC");
console.log("after NFC", composed.length, new TextEncoder().encode(composed).length);
Output
UTF-8 bytes 19
UTF-16 code units 12
code points 10
grapheme clusters 7
after NFC 11 18
const bad = new Uint8Array([0x61, 0xc0, 0xaf, 0xed, 0xa0, 0x80, 0x62]);
console.log(JSON.stringify(new TextDecoder().decode(bad)));

try {
  new TextDecoder("utf-8", { fatal: true }).decode(bad);
} catch (error) {
  console.log(error.name, error instanceof TypeError);
}

const withBom = new Uint8Array([0xef, 0xbb, 0xbf, 0x68, 0x69]);
console.log(new TextDecoder().decode(withBom).length);
console.log(new TextDecoder("utf-8", { ignoreBOM: true }).decode(withBom).length);

const lone = "a\uD800b";
console.log(lone.isWellFormed(), lone.toWellFormed() === "a\uFFFDb");
const encoded = new TextEncoder().encode(lone);
console.log([...encoded].map((byte) => byte.toString(16).padStart(2, "0")).join(" "));
Output
"a�����b"
TypeError true
2
3
false true
61 ef bf bd 62
  • Verdict: native. TextEncoder and TextDecoder of the WHATWG Encoding Standard convert between strings and UTF-8 bytes. Browsers, Node.js and Deno have them.
  • A JavaScript string is a sequence of UTF-16 code units. length counts code units. The spread [...text] iterates by code point. Intl.Segmenter with the granularity "grapheme" finds the grapheme clusters.
  • By default TextDecoder replaces each maximal subpart of an ill-formed sequence with U+FFFD. The option fatal: true makes it throw a TypeError.
  • The decoder removes a leading byte order mark. The option ignoreBOM: true keeps it in the string.
  • A string can hold a lone surrogate. TextEncoder writes it as EF BF BD, the encoding of U+FFFD. isWellFormed finds lone surrogates, and toWellFormed replaces them.
TypeScriptGitHub
type Result = { ok: true } | { ok: false; offset: number };

function sequenceLength(lead: number): number {
  if (lead <= 0x7f) return 1;
  if (lead >= 0xc2 && lead <= 0xdf) return 2;
  if (lead >= 0xe0 && lead <= 0xef) return 3;
  if (lead >= 0xf0 && lead <= 0xf4) return 4;
  return 0;
}

function secondByteRange(lead: number): [number, number] {
  switch (lead) {
    case 0xe0: return [0xa0, 0xbf];
    case 0xed: return [0x80, 0x9f];
    case 0xf0: return [0x90, 0xbf];
    case 0xf4: return [0x80, 0x8f];
    default: return [0x80, 0xbf];
  }
}

function validate(bytes: Uint8Array): Result {
  let index = 0;
  while (index < bytes.length) {
    const length = sequenceLength(bytes[index]);
    if (length === 0 || index + length > bytes.length) {
      return { ok: false, offset: index };
    }
    for (let next = 1; next < length; next++) {
      const [low, high] = next === 1 ? secondByteRange(bytes[index]) : [0x80, 0xbf];
      const byte = bytes[index + next];
      if (byte < low || byte > high) {
        return { ok: false, offset: index };
      }
    }
    index += length;
  }
  return { ok: true };
}

const samples: Record<string, number[]> = {
  "A e-acute euro clef": [0x41, 0xc3, 0xa9, 0xe2, 0x82, 0xac, 0xf0, 0x9d, 0x84, 0x9e],
  "overlong slash": [0x2f, 0xc0, 0xaf],
  "overlong euro": [0xe0, 0x82, 0xac],
  "surrogate D800": [0xed, 0xa0, 0x80],
  "above 10FFFF": [0xf4, 0x90, 0x80, 0x80],
  "truncated": [0x41, 0xe2, 0x82],
};

const strict = new TextDecoder("utf-8", { fatal: true });
for (const [name, list] of Object.entries(samples)) {
  const bytes = new Uint8Array(list);
  let agrees: boolean;
  try {
    strict.decode(bytes);
    agrees = validate(bytes).ok;
  } catch {
    agrees = !validate(bytes).ok;
  }
  console.log(name.padEnd(20), JSON.stringify(validate(bytes)), agrees);
}
Output
A e-acute euro clef  {"ok":true} true
overlong slash       {"ok":false,"offset":1} true
overlong euro        {"ok":false,"offset":0} true
surrogate D800       {"ok":false,"offset":0} true
above 10FFFF         {"ok":false,"offset":0} true
truncated            {"ok":false,"offset":1} true
  • Verdict: native. TypeScript runs on JavaScript, so it has TextEncoder, TextDecoder and Intl.Segmenter. The example is an idiom that shows the rules of the format.
  • The function validate follows Table 3-7 of the Unicode Standard. The lead byte gives the length. The range of the second byte depends on the lead byte, and this one check rejects overlong forms, surrogates and values above U+10FFFF.
  • The bytes C0, C1 and F5 to FF can never start a sequence, so sequenceLength returns 0 for them.
  • The last column compares the result with TextDecoder in its fatal mode. The two agree on each sample.
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	text := "nai\u0308ve \U0001F469\u200d\U0001F4BB"
	fmt.Println("bytes", len(text))
	fmt.Println("runes", utf8.RuneCountInString(text))
	fmt.Printf("byte 3 is %X, text[3:4] is %q\n", text[3], text[3:4])

	for index, r := range "a\u00e9\U0001D11E" {
		fmt.Printf("offset %d U+%04X %d bytes\n", index, r, utf8.RuneLen(r))
	}

	buffer := make([]byte, utf8.UTFMax)
	size := utf8.EncodeRune(buffer, 0x20AC)
	fmt.Printf("U+20AC % X\n", buffer[:size])
	size = utf8.EncodeRune(buffer, 0xD800)
	fmt.Printf("U+D800 % X\n", buffer[:size])
}
Output
bytes 19
runes 10
byte 3 is CC, text[3:4] is "\xcc"
offset 0 U+0061 1 bytes
offset 1 U+00E9 2 bytes
offset 3 U+1D11E 4 bytes
U+20AC E2 82 AC
U+D800 EF BF BD
package main

import (
	"fmt"
	"strings"
	"unicode/utf8"
)

func main() {
	bad := "a\xc0\xaf\xed\xa0\x80b"
	fmt.Println(utf8.ValidString(bad), utf8.RuneCountInString(bad))

	for index, r := range bad {
		if r == utf8.RuneError {
			fmt.Print(index, " ")
		}
	}
	fmt.Println()

	fmt.Printf("%q\n", string([]rune(bad)))
	fmt.Printf("%q\n", strings.ToValidUTF8(bad, "\uFFFD"))
}
Output
false 7
1 2 3 4 5
"a�����b"
"a�b"
  • Verdict: stdlib. A Go string is a sequence of bytes, and Go source files are UTF-8. The package unicode/utf8 encodes, decodes, counts and validates.
  • len counts bytes. utf8.RuneCountInString counts code points. An index such as text[2] gives one byte, and a slice can cut a character in half.
  • A for range loop over a string decodes one rune at a time and gives the byte offset of each rune. For an invalid byte it gives utf8.RuneError (U+FFFD) and moves one byte forward.
  • utf8.EncodeRune writes U+FFFD for a surrogate or a value above U+10FFFF.
  • The conversion to []rune gives one U+FFFD for each bad byte. strings.ToValidUTF8 replaces each run of bad bytes with one replacement string.
  • The standard library has no normalization and no grapheme segmentation. The module golang.org/x/text/unicode/norm does normalization.
RustGitHub
fn main() {
    let text = "nai\u{308}ve \u{1F469}\u{200D}\u{1F4BB}";
    println!("bytes {}", text.len());
    println!("chars {}", text.chars().count());
    println!("{:?} {:?}", text.get(0..3), text.get(0..4));
    println!("{} {}", text.is_char_boundary(3), text.is_char_boundary(4));

    for c in ['A', '\u{E9}', '\u{20AC}', '\u{1D11E}'] {
        let mut buffer = [0u8; 4];
        let bytes = c.encode_utf8(&mut buffer).as_bytes();
        println!("U+{:04X} {} {:02X?}", c as u32, c.len_utf8(), bytes);
    }
    println!("{:?} {:?}", char::from_u32(0xD800), char::from_u32(0x110000));
}
Output
bytes 19
chars 10
Some("nai") None
true false
U+0041 1 [41]
U+00E9 2 [C3, A9]
U+20AC 3 [E2, 82, AC]
U+1D11E 4 [F0, 9D, 84, 9E]
None None
fn main() {
    let samples: [&[u8]; 4] = [
        b"ok \xE2\x82\xAC",
        b"a\xC0\xAFb",
        b"a\xED\xA0\x80b",
        b"a\xE2\x82",
    ];
    for bytes in samples {
        match std::str::from_utf8(bytes) {
            Ok(text) => println!("valid {text:?}"),
            Err(error) => println!(
                "valid_up_to {} error_len {:?} lossy {:?}",
                error.valid_up_to(),
                error.error_len(),
                String::from_utf8_lossy(bytes)
            ),
        }
    }

    let owned = String::from_utf8(vec![0xEF, 0xBB, 0xBF, b'h', b'i']).unwrap();
    println!("{} {:?}", owned.chars().count(), owned.strip_prefix('\u{FEFF}'));
}
Output
valid "ok €"
valid_up_to 1 error_len Some(1) lossy "a��b"
valid_up_to 1 error_len Some(1) lossy "a���b"
valid_up_to 1 error_len None lossy "a�"
3 Some("hi")
  • Verdict: stdlib. The types str and String always hold valid UTF-8. The type char holds one Unicode scalar value, so it cannot hold a surrogate.
  • len counts bytes, and chars().count() counts scalar values. A range index must fall on a character boundary. get returns None at other offsets, and the index operator &text[0..4] panics there.
  • str::from_utf8 checks the bytes. Its error gives valid_up_to, the length of the valid prefix, and error_len. error_len is None when the input ends in the middle of a sequence, so a stream reader can wait for more bytes.
  • String::from_utf8_lossy replaces each maximal subpart of a bad sequence with U+FFFD.
  • A leading byte order mark stays in the string as U+FEFF. The program must remove it.
  • The standard library has no normalization and no grapheme segmentation. The crates unicode-normalization and unicode-segmentation do them.
CREATE TABLE word (label TEXT, value TEXT);
INSERT INTO word VALUES ('composed', 'caf' || char(0xE9));
INSERT INTO word VALUES ('decomposed', 'cafe' || char(0x301));
INSERT INTO word VALUES ('clef', char(0x1D11E));

SELECT label, length(value), octet_length(value), hex(value), unicode(substr(value, -1)) FROM word;
SELECT count(DISTINCT value) FROM word WHERE label <> 'clef';
Output
composed|4|5|636166C3A9|233
decomposed|5|6|63616665CC81|769
clef|1|4|F09D849E|119070
2
  • Verdict: native. A SQLite database stores text in UTF-8 by default. The function length counts characters, octet_length counts bytes, hex shows the bytes, and unicode and char convert between characters and code points.
  • SQLite compares text byte by byte by default. The composed and the decomposed forms of "café" look the same, but they are two distinct values. SQLite has no normalization function, so normalize the text before it goes into the database.
  • Other databases name the encoding in the definition of the database or the column. In MySQL, the character set utf8mb4 is UTF-8 with up to four bytes. The older name utf8 stores at most three bytes, so it cannot hold characters outside the BMP.
BashGitHub
word=$(printf 'caf\xc3\xa9')
printf '%s' "$word" | od -An -tx1 | head -n 1

LC_ALL=C
echo "C locale: ${#word}"
LC_ALL=en_US.UTF-8
echo "UTF-8 locale: ${#word}"

printf '%s' "$word" | wc -c | tr -d ' '
Output
           63  61  66  c3  a9
C locale: 5
UTF-8 locale: 4
5
  • Verdict: idiom. Bash passes bytes through, and it does not validate them.
  • The expansion ${#word} gives the length in characters. The variable LC_CTYPE, or LC_ALL, decides how Bash interprets characters. In the C locale each byte is a character, so "café" has five. In a UTF-8 locale it has four.
  • wc -c counts bytes in each locale.
  • The name of the UTF-8 locale differs between systems, such as en_US.UTF-8 or C.UTF-8. The command locale -a lists the locales of the system.

Versions

The bit patterns of the sequences of one to four bytes are the same in each RFC. The changes are in the range of code points and in the rules for invalid input.

Document Date Status Change
Thompson's proposal to X/Open September 1992 proposal the encoding, sent as the "modified FSS-UTF proposal"6
RFC 2044 October 1996 Informational UTF-8 as an RFC; sequences of up to six bytes8
RFC 2279 January 1998 Standards Track obsoletes RFC 2044; sequences of up to six bytes, for values up to 7FFFFFFF7
RFC 2277 (BCP 18) January 1998 Best Current Practice "Protocols MUST be able to use the UTF-8 charset"9
RFC 3629 (STD 63) November 2003 Internet Standard obsoletes RFC 2279; see below1

RFC 3629 changed these points of RFC 2279:1

  • It restricts the range to U+0000 to U+10FFFF, the range that UTF-16 can reach. So a sequence has at most four bytes.
  • It makes the Unicode Standard the source of the normative definition.
  • It turns the note against the decode of invalid sequences into a MUST NOT.
  • It adds the section on the BOM and the ABNF grammar.

ISO/IEC 10646 once allowed values up to U+7FFFFFFF, with sequences of up to six bytes. RFC 3629 warns that a buffer can overflow if a program does not limit the range to U+10FFFF.1

The WHATWG Encoding Standard is the reference for the web platform. It calls UTF-8 "the most appropriate encoding for interchange of Unicode". It says that new protocols and formats must use UTF-8 only.10 It defines the decode hooks "UTF-8 decode", which removes a leading BOM, "UTF-8 decode without BOM", and "UTF-8 decode without BOM or fail", which stops at the first error.10

Variants that are not UTF-8

  • CESU-8. It encodes each UTF-16 code unit of a surrogate pair as its own three-byte sequence. A code point above U+FFFF takes six bytes. RFC 3629 says that this form is not valid UTF-8.1
  • Modified UTF-8. Java uses it in DataOutput.writeUTF, in class files and in JNI. It writes U+0000 as the two bytes C0 80, so the encoded string has no zero byte. It uses only the forms of one, two and three bytes, and it writes a supplementary character as a surrogate pair.19

Pitfalls

  • Length in the wrong unit. len in Go and Rust counts bytes. length in JavaScript, Java and C# counts UTF-16 code units. len in Python counts code points. None of them counts what a reader sees as characters. Use a grapheme segmenter to limit the length of a name or to move a cursor.12
  • A cut in the middle of a character. A byte index can fall inside a sequence. A truncation to a fixed number of bytes can leave half a character at the end. The example files for Go and Rust show this.
  • Silent replacement. The default decoders of Python (with errors="replace"), Go, Java, C#, JavaScript and Rust (from_utf8_lossy) put U+FFFD in place of bad input and report nothing. Data is lost, and the count of U+FFFD differs between libraries. Use the strict mode at a trust boundary.
  • Overlong forms and surrogates. A hand decoder that only follows the bit layout accepts C0 80 as U+0000 and ED A0 80 as a surrogate. Check the ranges of Table 3-7, or use the decoder of the standard library.2
  • Lone surrogates from UTF-16 strings. A string in JavaScript, Java or C# is a sequence of UTF-16 code units, so it can hold a lone surrogate.233422 UTF-8 cannot encode it. The encoders of JavaScript and C# write U+FFFD in its place, so the text changes on the way out.
  • The BOM. Some programs write EF BB BF at the start of a UTF-8 file. Windows PowerShell does so for each Unicode encoding other than UTF-7.31 A parser that does not expect it sees U+FEFF as part of the first field or key. The first column of a CSV file then has a different name. Read with utf-8-sig in Python, or remove U+FEFF at the start.13
  • Normalization. The composed and the decomposed forms of "é" are different strings. A lookup, a unique key or a password check can fail on equal text. RFC 3629 says this can affect security, for example when a program matches an identifier against an access control list.1 Normalize the text at the boundary.
  • The wrong decoder. Text in UTF-8 that a program reads as Windows-1252 or ISO 8859-1 turns "é" into "é" and the BOM into "". The reverse error turns each such byte into U+FFFD. Name the encoding in each call that reads or writes text, and do not depend on the default of the platform.420
  • MySQL utf8. In MySQL the character set utf8mb3 has at most three bytes for each character, so it cannot store characters outside the BMP. The name utf8 is a deprecated alias for utf8mb3. Use utf8mb4.27

Tools and libraries

Language Verdict Encode and decode Count
Python stdlib str.encode("utf-8"), bytes.decode("utf-8", errors=...)13 len counts code points; unicodedata.normalize14
JavaScript, TypeScript native TextEncoder, TextDecoder with fatal and ignoreBOM24 length counts UTF-16 units; Intl.Segmenter for graphemes25; isWellFormed, normalize23
Go stdlib Go source is UTF-8, and string holds bytes16 utf8.RuneCountInString, utf8.ValidString15
Rust stdlib str::from_utf8, String::from_utf8_lossy17 len counts bytes; chars().count(); char is a scalar value18
Java stdlib getBytes(StandardCharsets.UTF_8), CharsetDecoder34 length, codePointCount, BreakIterator, Normalizer
C# stdlib Encoding.UTF8, new UTF8Encoding(false, true)21 Length, EnumerateRunes, StringInfo22
C, C++ idiom u8 literals; the UTF-8 facets of <codecvt> are deprecated and removed from the working draft33 libraries such as ICU and simdutf
SQL native SQLite stores text as UTF-8 by default26 length, octet_length, unicode, char26
Kotlin stdlib decodeToString, with throwOnInvalidSequence = true for a strict decode30 as on the JVM
PowerShell stdlib -Encoding utf8NoBOM or utf8BOM on the file cmdlets31 the .NET string methods
Bash idiom the shell passes the bytes through ${#name} counts characters in the locale32
HTML, CSS native the document must be UTF-828; a style sheet falls back to UTF-829 n/a

The HTML standard says that the encoding of a document "must be UTF-8", whether or not it has a declaration such as <meta charset="utf-8">.28 CSS reads a BOM first, then the HTTP header, then a @charset "…"; at the very start of the file, then the encoding of the document that links the style sheet, and else uses UTF-8.29

References

  1. F. Yergeau, RFC 3629: UTF-8, a transformation format of ISO 10646, November 2003 (STD 63), 1 Introduction; 3 UTF-8 definition; 4 Syntax of UTF-8 Byte Sequences; 6 Byte order mark (BOM); 7 Examples; 10 Security Considerations; 12 Changes from RFC 2279
  2. The Unicode Standard, Version 18.0.0, Chapter 3, Conformance, 3.8 Surrogates; 3.9 Unicode Encoding Forms (D76, D92, Table 3-6, Table 3-7); 3.9.6 U+FFFD Substitution of Maximal Subparts; 3.10 Unicode Encoding Schemes (D95)
  3. The Unicode Standard, Version 18.0.0, Chapter 2, General Structure, 2.5 Encoding Forms, UTF-8 (variable width, data size, binary sorting)
  4. The Unicode Standard, Version 18.0.0, Chapter 23, Special Areas and Format Characters, 23.8 Specials, Byte Order Mark (BOM)
  5. R. Pike and K. Thompson, Hello World or Καλημέρα κόσμε or こんにちは 世界, Proc. of the Winter 1993 USENIX Conf., pp. 43-50, the sections Standards, UTF and the notes
  6. Rob Pike, UTF-8 history, e-mail of 30 April 2003, with the mail of September 1992 from the Plan 9 archive, the first message; the mail of Tue Sep 8 03:22:07 EDT 1992
  7. F. Yergeau, RFC 2279: UTF-8, a transformation format of ISO 10646, January 1998, the header; 1 Introduction; 2 UTF-8 definition
  8. F. Yergeau, RFC 2044: UTF-8, a transformation format of Unicode and ISO 10646, October 1996, the header
  9. H. Alvestrand, RFC 2277: IETF Policy on Character Sets and Languages, January 1998 (BCP 18), 3.1 What charset to use
  10. WHATWG, Encoding Standard, Living Standard, Preface; 4.2 Names and labels; 6 Hooks for standards; 8.1.1 UTF-8 decoder
  11. Unicode Standard Annex, 1.1 Canonical and Compatibility Equivalence; 1.2 Normalization Forms, Table 1
  12. Unicode Standard Annex, 3 Grapheme Cluster Boundaries, Table 1a
  13. The Python Standard Library, codecs, Python 3.14, Error Handlers; Encodings and Unicode; encodings.utf_8_sig
  14. The Python Standard Library, unicodedata, Python 3.14, unicodedata.normalize
  15. Go standard library, package unicode/utf8, RuneError; EncodeRune; DecodeRuneInString; RuneCount; ValidString
  16. The Go Programming Language Specification, Source code representation; For statements with range clause
  17. Rust standard library, std::str::Utf8Error, valid_up_to; error_len
  18. Rust standard library, primitive type char, Validity and Layout
  19. Java SE 25 API, java.io.DataInput, Modified UTF-8
  20. JEP 400: UTF-8 by Default, Summary; Goals
  21. .NET API, UTF8Encoding Class, Remarks (the table of constructors, the BOM and error detection)
  22. .NET documentation, Character encoding in .NET, The string and char types; Grapheme clusters
  23. ECMA-262, ECMAScript 2026 Language Specification, 6.1.4 The String Type; 22.1.3.10 String.prototype.isWellFormed; 22.1.3.15 String.prototype.normalize; 22.1.3.31 String.prototype.toWellFormed
  24. MDN Web Docs, TextDecoder() constructor, the options fatal and ignoreBOM
  25. MDN Web Docs, Intl.Segmenter, the description
  26. SQLite, Built-In Scalar SQL Functions, length(X); octet_length(X); hex(X); unicode(X); char(X1,X2,...,XN)
  27. MySQL 8.4 Reference Manual, 12.9.2 The utf8mb3 Character Set (3-Byte UTF-8 Unicode Encoding), the list of characteristics
  28. WHATWG, HTML Living Standard, 4.2.5.4 Specifying the document's character encoding
  29. CSS Syntax Module Level 3, Editor's Draft, 3.2 The input byte stream (determine the fallback encoding); 8.3 The @charset Rule
  30. Kotlin standard library, decodeToString, the two signatures and the parameter throwOnInvalidSequence
  31. PowerShell documentation, about_Character_Encoding, the values of the Encoding parameter; the default encoding
  32. GNU Bash Reference Manual, 3.5.3 Shell Parameter Expansion, ${#parameter}
  33. Working Draft, Programming Languages, C++, [depr.locale.stdcvt], the stable name (the subclause was removed)
  34. Java SE 25 API, java.lang.String, the class description; String(byte[], Charset); getBytes(Charset)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3W23QF/text.yaml