---
title: "Text Encodings: From ASCII to UTF-8"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 5
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/5-text-encodings-from-ascii-to-utf-8
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 5 — Text Encodings: From ASCII to UTF-8

The town’s café sends its weekly menu to the notice board at the station, a screen run by a small computer. On Monday the board shows **Lighthouse CafÃ©**. The menu file has not changed, the screen is not broken, and nobody typed an *Ã*. The file and the board simply disagree about what the bytes of the file mean.

A text file is a sequence of bytes, and a byte is a number from $0$ to $255$. Turning letters into numbers and back needs a table that both sides agree on. This chapter follows these tables from the first one, which had room for the English alphabet only, to the one used today for every script in the world, and explains, byte by byte, how *é* became *Ã©*.

**You already know.**

A computer stores each [character](#def-g10-text-encodings-code-point) as a number, its code, taken from a code table (Book 1, grade 5). In Python a string is a sequence of [characters](#def-g10-text-encodings-code-point), `ord(c)` gives the code of a [character](#def-g10-text-encodings-code-point) and `chr(n)` the [character](#def-g10-text-encodings-code-point) of a code (Book 1, grade 7). A byte is written with two hexadecimal digits, from `00` to `FF` (Book 1, grade 8).

## 5.1 Characters, code points and bytes

Two questions must be kept apart: which number stands for a [character](#def-g10-text-encodings-code-point), and which bytes stand for that number.

**Definition 5.1 (Character, code point).**

A *character* is a unit of written text: a letter, a digit, a punctuation sign, a space, an emoji. A *code point* is the number that a code table gives to a character. Code points are written `U+` followed by at least four hexadecimal digits: `U+0041` is *A*, `U+00E9` is *é*.

**Definition 5.2 (Character encoding).**

A *character encoding* is a rule that turns a sequence of [characters](#def-g10-text-encodings-code-point) into a sequence of bytes (*encoding*) and back (*decoding*). A text file holds bytes only; reading it as text needs the encoding it was written with.

Python keeps the two worlds apart: a `str` holds [characters](#def-g10-text-encodings-code-point), a `bytes` value holds bytes, and the methods `encode` and `decode` cross between them, always with the name of an [encoding](#def-g10-text-encodings-encoding).

## 5.2 ASCII on seven bits

**Definition 5.3 (ASCII).**

*ASCII* (American Standard Code for Information Interchange, 1968) is a code table of $128$ [characters](#def-g10-text-encodings-code-point), numbered from $0$ to $127$, so that each fits in $7$ bits. Codes $0$ to $31$ and $127$ are *control [characters](#def-g10-text-encodings-code-point)* (line feed, tabulation, …), which are not printed; codes $32$ to $126$ are the space, the digits, the English letters in both cases and punctuation. As an [encoding](#def-g10-text-encodings-encoding), ASCII stores each [character](#def-g10-text-encodings-code-point) in one byte whose leftmost bit is $0$.

![The ASCII table in rows of 16: the row gives the first hexadecimal digit, the column the second. Digits (blue) start at 30, capital letters (orange) at 41 and small letters (green) at 61, exactly 20 hexadecimal, that is 32, further on.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-text-encodings/fig-b3334175c6a7.svg)

*The [ASCII](#def-g10-text-encodings-ascii) table in rows of $16$: the row gives the first hexadecimal digit, the column the second. Digits (blue) start at `30`, capital letters (orange) at `41` and small letters (green) at `61`, exactly `20` hexadecimal, that is $32$, further on.*

The layout was designed with care: the digit $d$ has code $48 + d$, and a small letter’s code is the capital’s plus $32$, a single bit.

```python
for c in "Aa0 ~":
    print(repr(c), ord(c), hex(ord(c)), format(ord(c), "07b"))
print(chr(66), chr(98), chr(0x41 + 25))
print(ord("a") - ord("A"), chr(ord("g") - 32))
```

***Listing 5.1.** Codes in decimal, hexadecimal and on $7$ bits. code/grade-10/05-text-encodings/listings/ord_chr.py*

```
$ python ord_chr.py
'A' 65 0x41 1000001
'a' 97 0x61 1100001
'0' 48 0x30 0110000
' ' 32 0x20 0100000
'~' 126 0x7e 1111110
B b Z
32 G
```

***Output 5.1.** *A* and *a* differ only in the bit worth $32$.*

```python
print("     " + " ".join(f"{c:X}" for c in range(16)))
for row in range(2, 8):
    cells = []
    for col in range(16):
        code = 16 * row + col
        cells.append(chr(code) if code < 127 else ".")
    print(f"{row:X}x   " + " ".join(cells))
```

***Listing 5.2.** Printing the table of printable [characters](#def-g10-text-encodings-code-point). code/grade-10/05-text-encodings/listings/ascii_table.py*

```
$ python ascii_table.py
     0 1 2 3 4 5 6 7 8 9 A B C D E F
2x     ! " # $ % & ' ( ) * + , - . /
3x   0 1 2 3 4 5 6 7 8 9 : ; < = > ?
4x   @ A B C D E F G H I J K L M N O
5x   P Q R S T U V W X Y Z [ \ ] ^ _
6x   ` a b c d e f g h i j k l m n o
7x   p q r s t u v w x y z { | } ~ .
```

***Output 5.2.** Rows `2x` to `7x`; the dot stands for code $127$, which is not printable.*

[ASCII](#def-g10-text-encodings-ascii) has no *é*, no *ñ*, no *ß*, and none of the world’s other scripts. It was enough for the teleprinters of the 1960s, which wrote English, and too little for nearly everyone else.

![A Teletype ASR-33 teleprinter at the Computer History Museum: a keyboard below, and a printer on a roll of paper above. Photograph: Arnold Reinhold, CC BY-SA 3.0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-text-encodings/img-b0921630a00c.jpg)

*A Teletype ASR-33 teleprinter at the Computer History Museum: a keyboard below, and a printer on a roll of paper above. Photograph: Arnold Reinhold, CC BY-SA 3.0.*

## 5.3 One-byte extensions and their conflicts

A byte has $8$ bits, and [ASCII](#def-g10-text-encodings-ascii) uses only codes $0$ to $127$. The obvious idea was to give the other $128$ values, from $128$ to $255$, to the letters that [ASCII](#def-g10-text-encodings-ascii) lacks.

**Definition 5.4 (One-byte extension of ASCII).**

A *one-byte extension of ASCII* is an [encoding](#def-g10-text-encodings-encoding) that keeps [ASCII](#def-g10-text-encodings-ascii) for bytes $0$ to $127$ and gives bytes $128$ to $255$ to other [characters](#def-g10-text-encodings-code-point), one [character](#def-g10-text-encodings-code-point) per byte.

The best known is *ISO-8859-1*, also called Latin-1 (1987), for Western European languages: in it, byte `E9` is *é*.

The trouble is that there were dozens of such tables, one for Greek, one for Cyrillic, one for each make of computer, and each gave the same byte a different meaning. A file does not say which table it was written with.

```python
word = "été"
for encoding in ("latin-1", "utf-8", "utf-16-le"):
    data = word.encode(encoding)
    print(f"{encoding:9}  {len(data)} bytes  {data.hex(' ')}")

data = bytes([0x63, 0x61, 0x66, 0xE9])
print(data.decode("latin-1"), ascii(data.decode("mac_roman")))
```

***Listing 5.3.** One word, three [encodings](#def-g10-text-encodings-encoding); one byte, two tables. code/grade-10/05-text-encodings/listings/latin1_vs_utf8.py*

```
$ python latin1_vs_utf8.py
latin-1    3 bytes  e9 74 e9
utf-8      5 bytes  c3 a9 74 c3 a9
utf-16-le  6 bytes  e9 00 74 00 e9 00
café 'caf\xc8'
```

***Output 5.3.** Byte `E9` is *é* in Latin-1 and *È*, [code point](#def-g10-text-encodings-code-point) `U+00C8`, in an old table of another make of computer, `mac_roman`. The function `ascii` writes a [character](#def-g10-text-encodings-code-point) that is not [ASCII](#def-g10-text-encodings-ascii) as an escape `\x..`.*

![The word été in three encodings. The shaded bytes stand for é; t is one byte in the first two and two bytes in UTF-16, which uses at least two bytes for every character.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-text-encodings/fig-df83976d071f.svg)

*The word *été* in three [encodings](#def-g10-text-encodings-encoding). The shaded bytes stand for *é*; *t* is one byte in the first two and two bytes in UTF-16, which uses at least two bytes for every [character](#def-g10-text-encodings-code-point).*

## 5.4 Unicode and UTF-8

The way out was to stop making tables and make one.

**Definition 5.5 (Unicode).**

*Unicode* is a single code table for the [characters](#def-g10-text-encodings-code-point) of every writing system, first published in 1991. Its [code points](#def-g10-text-encodings-code-point) run from `U+0000` to `U+10FFFF`; the first $128$ are those of [ASCII](#def-g10-text-encodings-ascii) and the first $256$ those of Latin-1. Unicode says which number each [character](#def-g10-text-encodings-code-point) has, not which bytes store it: that is the job of an [encoding](#def-g10-text-encodings-encoding) of Unicode.

**Facts as of 2026.**

[Unicode](#def-g10-text-encodings-unicode) 18.0, released in September 2026, contains $172{,}808$ [characters](#def-g10-text-encodings-code-point). A new version comes out about once a year, mostly adding [characters](#def-g10-text-encodings-code-point) of historic scripts and new emoji.

Storing every [code point](#def-g10-text-encodings-code-point) in $4$ bytes would work but would make every English text four times larger. The [encoding](#def-g10-text-encodings-encoding) used by most of the web and by almost every text file today uses between one and four bytes.

**Definition 5.6 (UTF-8).**

*UTF-8* encodes each [code point](#def-g10-text-encodings-code-point) in $1$ to $4$ bytes. Its bits are placed in the free positions `x` of the patterns of the figure below, from left to right. The first byte tells how many bytes follow; every following byte, a *continuation byte*, starts with the bits `10`.

![The four patterns of UTF-8, their fixed bits in red, and é encoded by hand: its 11 bits fill the x of the two-byte pattern.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-text-encodings/fig-0dcfd8f62bda.svg)

*The four patterns of [UTF-8](#def-g10-text-encodings-utf8), their fixed bits in red, and *é* encoded by hand: its $11$ bits fill the `x` of the two-byte pattern.*

(The [code points](#def-g10-text-encodings-code-point) `U+D800` to `U+DFFF` are left out: they are reserved for UTF-16, which writes the [code points](#def-g10-text-encodings-code-point) above `U+FFFF` as a pair of such numbers.)

The listing builds the bytes with the shifts and [masks](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-mask) of the chapter on machine integers, and checks them against Python’s own encoder.

```python
def utf8_encode(cp):
    """Return the UTF-8 bytes of the code point cp, 0 <= cp <= 0x10FFFF."""
    if cp < 0x80:
        return bytes([cp])
    if cp < 0x800:
        return bytes([0b110_00000 | cp >> 6, 0b10_000000 | cp & 0x3F])
    if cp < 0x10000:
        return bytes([0b1110_0000 | cp >> 12,
                      0b10_000000 | (cp >> 6) & 0x3F,
                      0b10_000000 | cp & 0x3F])
    return bytes([0b11110_000 | cp >> 18,
                  0b10_000000 | (cp >> 12) & 0x3F,
                  0b10_000000 | (cp >> 6) & 0x3F,
                  0b10_000000 | cp & 0x3F])


for cp in (0x41, 0xE9, 0x20AC, 0x1F600):
    mine = utf8_encode(cp)
    print(f"U+{cp:04X}  {mine.hex(' '):12}  same as Python: {mine == chr(cp).encode()}")
```

***Listing 5.4.** [UTF-8](#def-g10-text-encodings-utf8) by hand. code/grade-10/05-text-encodings/listings/utf8_by_hand.py*

```
$ python utf8_by_hand.py
U+0041  41            same as Python: True
U+00E9  c3 a9         same as Python: True
U+20AC  e2 82 ac      same as Python: True
U+1F600  f0 9f 98 80   same as Python: True
```

***Output 5.4.** *A*, *é*, the euro sign and an emoji (a smiling face): $1$, $2$, $3$ and $4$ bytes.*

**Proposition 5.7 (Properties of UTF-8).**

1. An [ASCII](#def-g10-text-encodings-ascii) text is its own [UTF-8](#def-g10-text-encodings-utf8) [encoding](#def-g10-text-encodings-encoding) , byte for byte.
2. No byte of a [character](#def-g10-text-encodings-code-point) of two or more bytes is below $128$ , so an [ASCII](#def-g10-text-encodings-ascii) byte in [UTF-8](#def-g10-text-encodings-utf8) is always an [ASCII](#def-g10-text-encodings-ascii) [character](#def-g10-text-encodings-code-point) .
3. A continuation byte is never the first byte of a [character](#def-g10-text-encodings-code-point) , so a program that starts reading in the middle of a text finds the next [character](#def-g10-text-encodings-code-point) boundary by skipping at most three bytes.

**Proof.** (1) [Code points](#def-g10-text-encodings-code-point) below $128$ use the one-byte pattern `0xxxxxxx`, which is the [ASCII](#def-g10-text-encodings-ascii) byte itself. (2) In a pattern of two or more bytes, every byte starts with a $1$ bit, so it is at least $128$. (3) A continuation byte starts with `10`; a first byte starts with `0`, `110`, `1110` or `11110`, never `10`. A [character](#def-g10-text-encodings-code-point) has at most three continuation bytes. ∎

## 5.5 Garbled text, and bytes in Python

Now the notice board can be explained.

**Definition 5.8 (Mojibake).**

*Mojibake* (garbled text, from a Japanese word) is the text obtained when bytes are decoded with an [encoding](#def-g10-text-encodings-encoding) other than the one they were written with.

```python
name = "Lighthouse Café"
data = name.encode("utf-8")
print(data.hex(" "))
wrong = data.decode("latin-1")
print(len(name), len(wrong), ascii(wrong))
print(wrong.encode("latin-1").decode("utf-8"))
```

***Listing 5.5.** The café’s name, written in [UTF-8](#def-g10-text-encodings-utf8) and read as Latin-1. code/grade-10/05-text-encodings/listings/mojibake.py*

```
$ python mojibake.py
4c 69 67 68 74 68 6f 75 73 65 20 43 61 66 c3 a9
15 16 'Lighthouse Caf\xc3\xa9'
Lighthouse Café
```

***Output 5.5.** The wrong reading has one [character](#def-g10-text-encodings-code-point) more than the name: the two bytes of *é* became two [characters](#def-g10-text-encodings-code-point), `\xc3` and `\xa9`. [Encoding](#def-g10-text-encodings-encoding) back and decoding right repairs it.*

![The path from é to Ã©: written with one encoding, read with another. In Latin-1, byte C3 is Ã and byte A9 is the copyright sign ©.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-text-encodings/fig-7a78a3f298c1.svg)

*The path from *é* to *Ã©*: written with one [encoding](#def-g10-text-encodings-encoding), read with another. In Latin-1, byte `C3` is *Ã* and byte `A9` is the copyright sign *©*.*

**Method 5.9 (Recognising the encoding of garbled text).**

1. An accented letter replaced by two [characters](#def-g10-text-encodings-code-point) , the first often *Ã* or *Â* : [UTF-8](#def-g10-text-encodings-utf8) bytes read as Latin-1 (or as a close one-byte table). Repair: encode with Latin-1, decode with [UTF-8](#def-g10-text-encodings-utf8) .
2. A replacement sign, or the error `UnicodeDecodeError` : one-byte-table bytes read as [UTF-8](#def-g10-text-encodings-utf8) . Decode with the right one-byte table.
3. Three or four [characters](#def-g10-text-encodings-code-point) for one letter: the mistake was made twice; repair once per layer.

Decoding does not always succeed. Byte `E9` starts a three-byte [character](#def-g10-text-encodings-code-point) in [UTF-8](#def-g10-text-encodings-utf8), so a Latin-1 *é* at the end of a text is an incomplete [UTF-8](#def-g10-text-encodings-utf8) [character](#def-g10-text-encodings-code-point).

```python
data = "Café".encode("latin-1")
print(data)
print(data.decode("utf-8", errors="backslashreplace"))
print(data.decode("utf-8"))
```

***Listing 5.6.** Latin-1 bytes read as [UTF-8](#def-g10-text-encodings-utf8). code/grade-10/05-text-encodings/listings/decode_error.py*

```
$ python decode_error.py
b'Caf\xe9'
Caf\xe9
Traceback (most recent call last):
  File "decode_error.py", line 4, in <module>
    print(data.decode("utf-8"))
          ^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: unexpected end of data
[exit status 1]
```

***Output 5.6.** `errors="backslashreplace"` writes the bad byte as an escape; without it, decoding stops.*

With `errors="replace"`, Python puts the replacement [character](#def-g10-text-encodings-code-point) `U+FFFD`, usually drawn as a question mark in a diamond, in place of each bad byte; with the default, `errors="strict"`, it stops.

**Method 5.10 (Reading and writing text files).**

Always name the [encoding](#def-g10-text-encodings-encoding): `open(name, encoding="utf-8")`, `Path(name).read_text(encoding="utf-8")`. Without it, Python uses the system’s default, which is not the same on every computer. To convert a file, read it with its old [encoding](#def-g10-text-encodings-encoding) and write it with the new one.

```python
from pathlib import Path

text = "Lighthouse Café\ncrêpes, 4 \u20ac\n"
Path("menu.txt").write_text(text, encoding="cp1252")

old = Path("menu.txt").read_text(encoding="cp1252")
Path("menu-utf8.txt").write_text(old, encoding="utf-8")

for name in ("menu.txt", "menu-utf8.txt"):
    print(name, Path(name).stat().st_size, "bytes")
print(Path("menu.txt").read_bytes()[-4:].hex(" "))
print(Path("menu-utf8.txt").read_bytes()[-6:].hex(" "))
```

***Listing 5.7.** Converting a menu from a one-byte table to [UTF-8](#def-g10-text-encodings-utf8). code/grade-10/05-text-encodings/listings/convert_file.py*

```
$ python convert_file.py
menu.txt 28 bytes
menu-utf8.txt 32 bytes
34 20 80 0a
34 20 e2 82 ac 0a
```

***Output 5.7.** *é*, *ê* and the euro sign take one byte each in the old file and $2$, $2$ and $3$ bytes in [UTF-8](#def-g10-text-encodings-utf8): $4$ bytes more.*

The table used here, `cp1252`, is a one-byte table close to Latin-1 that has the euro sign at byte `80`.

## 5.6 Exercises

**Exercise 5.1 ★.**

What do `ord("A")`, `chr(97)`, `ord("9") - ord("0")` and `chr(ord("A") + 2)` return?

**Solution of Exercise 5.1.**

`65`, `"a"`, `9` (the digits are consecutive from code $48$), and `"C"`.

**Exercise 5.2 ★.**

Give the bytes, in hexadecimal, of the word *été* in Latin-1 and in [UTF-8](#def-g10-text-encodings-utf8), using the figure of [UTF-8](#def-g10-text-encodings-utf8) patterns, and check them against the listing.

**Solution of Exercise 5.2.**

In Latin-1 each letter is one byte: `E9 74 E9`. In [UTF-8](#def-g10-text-encodings-utf8), *t* is `74` and *é* is `C3 A9`, as the figure computes: `C3 A9 74 C3 A9`. The listing prints the same bytes.

**Exercise 5.3 ★.**

What do `len("Café")`, `len("Café".encode("utf-8"))` and `len("Café".encode("latin-1"))` return? Explain the difference.

**Solution of Exercise 5.3.**

`4`, `5` and `4`. A string counts [characters](#def-g10-text-encodings-code-point); `bytes` count bytes. *é* takes two bytes in [UTF-8](#def-g10-text-encodings-utf8) and one in Latin-1; the other three letters take one byte in both.

**Exercise 5.4 ★.**

Write the codes of *A* and *a* on $7$ bits and show that they differ by one bit. Deduce a way to change the case of an [ASCII](#def-g10-text-encodings-ascii) letter with one [bitwise operation](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-bitwise).

**Solution of Exercise 5.4.**

*A* is `1000001` ($65$) and *a* is `1100001` ($97$): they differ only in the bit worth $32$. For an [ASCII](#def-g10-text-encodings-ascii) letter `c`, `chr(ord(c) ^ 32)` changes its case, `chr(ord(c) | 32)` makes it small and `chr(ord(c) & ~32)` makes it capital.

**Exercise 5.5 ★.**

Write `is_ascii(s)`, which tells whether every [character](#def-g10-text-encodings-code-point) of the string `s` is an [ASCII](#def-g10-text-encodings-ascii) [character](#def-g10-text-encodings-code-point), using `ord`.

**Solution of Exercise 5.5.**

In `exercises/is_ascii.py`: for each [character](#def-g10-text-encodings-code-point) `c` of `s`, if `ord(c) >= 128`, return `False`; after the loop, return `True`. The empty string is [ASCII](#def-g10-text-encodings-ascii). The tests compare it with Python’s `s.isascii()`.

**Exercise 5.6 ★★.**

Decode by hand the [UTF-8](#def-g10-text-encodings-utf8) bytes `63 72 C3 AA 70 65`: split them into [characters](#def-g10-text-encodings-code-point) with the first bytes, then compute each [code point](#def-g10-text-encodings-code-point).

**Solution of Exercise 5.6.**

`63` and `72` are below `80`: *c* and *r*. `C3` starts with `110`, so it begins a two-byte [character](#def-g10-text-encodings-code-point) with `AA`: the free bits are `00011` and `101010`, that is `000 1110 1010` $=$ `EA`, the [code point](#def-g10-text-encodings-code-point) `U+00EA`, *ê*. Then `70` is *p* and `65` is *e*: the word is *crêpe*.

**Exercise 5.7 ★★.**

Write `utf8_length(cp)`, which returns the number of [UTF-8](#def-g10-text-encodings-utf8) bytes of a [code point](#def-g10-text-encodings-code-point), and test it against `len(chr(cp).encode())`.

**Solution of Exercise 5.7.**

Compare with the pattern boundaries: $1$ below `0x80`, $2$ below `0x800`, $3$ below `0x10000`, $4$ otherwise (`exercises/utf8_length.py`). The tests check it on $500$ random [code points](#def-g10-text-encodings-code-point).

**Exercise 5.8 ★★.**

A program reads a [UTF-8](#def-g10-text-encodings-utf8) file of town names with `open(name, encoding="latin-1")` and prints *Lighthouse CafÃ©*. Which item of the method on garbled text is this? Correct the program, and say how to repair a string already read wrongly.

**Solution of Exercise 5.8.**

Item 1: [UTF-8](#def-g10-text-encodings-utf8) bytes read as Latin-1. The program should open the file with `encoding="utf-8"`. A string already read wrongly is repaired with `s.encode("latin-1").decode("utf-8")`, which gives back the bytes of the file and decodes them correctly.

**Exercise 5.9 ★★.**

The bytes `43 61 66 E9 20 63 72 EA 70 65` are *Café crêpe* in Latin-1. What does decoding them as [UTF-8](#def-g10-text-encodings-utf8) with `errors="replace"` return? How many replacement [characters](#def-g10-text-encodings-code-point) appear, and why does the error handler matter for a program that reads files from many sources?

**Solution of Exercise 5.9.**

The text *Caf*, a replacement [character](#def-g10-text-encodings-code-point), *cr*, a replacement [character](#def-g10-text-encodings-code-point), *pe* (`ascii` writes it `’Caf\ufffd cr\ufffdpe’`): two replacement [characters](#def-g10-text-encodings-code-point) `U+FFFD`, one for each of the bytes `E9` and `EA`: each starts a three-byte [UTF-8](#def-g10-text-encodings-utf8) [character](#def-g10-text-encodings-code-point) but is followed by an [ASCII](#def-g10-text-encodings-ascii) byte, so it is invalid on its own. A program that reads files from many sources must decide what a bad byte does: stop (`strict`), so that the mistake is noticed, or go on (`replace`), so that one bad byte does not lose the whole file.

**Exercise 5.10 ★★.**

How many [code points](#def-g10-text-encodings-code-point) can the two-byte pattern of [UTF-8](#def-g10-text-encodings-utf8) hold in its $11$ free bits? Why does [UTF-8](#def-g10-text-encodings-utf8) use it only for `U+0080` to `U+07FF`, and how many [code points](#def-g10-text-encodings-code-point) is that?

**Solution of Exercise 5.10.**

$11$ free bits hold $2^{11} = 2048$ values. [Code points](#def-g10-text-encodings-code-point) below `U+0080` must use the one-byte pattern, the shortest one (RFC 3629 forbids longer forms; that is why the bytes `C0` and `C1` never appear), so the two-byte pattern serves `U+0080` to `U+07FF`: $2048 - 128 = 1920$ [code points](#def-g10-text-encodings-code-point).

**Exercise 5.11 ★★.**

To fit a 4-byte field of a form, a program keeps the first $4$ bytes of a name’s [UTF-8](#def-g10-text-encodings-utf8) [encoding](#def-g10-text-encodings-encoding) and decodes them. For *Café* it stops with an error. Explain, and write `cut(text, n)`, which returns the longest beginning of `text` whose [UTF-8](#def-g10-text-encodings-utf8) [encoding](#def-g10-text-encodings-encoding) has at most `n` bytes.

**Solution of Exercise 5.11.**

The [UTF-8](#def-g10-text-encodings-utf8) bytes of *Café* are `43 61 66 C3 A9`; the first $4$ keep `C3` without its continuation byte, and decoding stops at an incomplete [character](#def-g10-text-encodings-code-point). The function `cut` of `exercises/cut_bytes.py` keeps the first $n$ bytes, walks back over continuation bytes to the first byte of the last [character](#def-g10-text-encodings-code-point), and drops that [character](#def-g10-text-encodings-code-point) if its pattern needs more bytes than are left. On *Café* with $n = 4$ it returns *Caf*. The tests check it on $300$ random texts.

**Exercise 5.12 ★★★.**

Write `utf8_decode(data)`, which returns the list of [code points](#def-g10-text-encodings-code-point) of valid [UTF-8](#def-g10-text-encodings-utf8) bytes, with the shifts and [masks](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-mask) of the chapter on machine integers, and test it against Python’s `decode` on random [code points](#def-g10-text-encodings-code-point).

**Solution of Exercise 5.12.**

In `exercises/utf8_decode.py`: read the first byte `b`; if `b < 0x80` the [character](#def-g10-text-encodings-code-point) has one byte and its [code point](#def-g10-text-encodings-code-point) is `b`; if `b >> 5 == 0b110`, two bytes and the [code point](#def-g10-text-encodings-code-point) starts with `b & 0x1F`; if `b >> 4 == 0b1110`, three bytes and `b & 0x0F`; otherwise four bytes and `b & 0x07`. For each continuation byte, shift the [code point](#def-g10-text-encodings-code-point) $6$ places left and add the byte’s $6$ low bits, `data[i + k] & 0x3F`. The tests decode $500$ random [code points](#def-g10-text-encodings-code-point) and compare with Python.

**Exercise 5.13 ★★★.**

Prove that in valid [UTF-8](#def-g10-text-encodings-utf8) a sequence of bytes that is the [encoding](#def-g10-text-encodings-encoding) of a [character](#def-g10-text-encodings-code-point) never appears inside the [encoding](#def-g10-text-encodings-encoding) of a longer [character](#def-g10-text-encodings-code-point). Deduce that searching for the bytes of a word inside the bytes of a text never finds a false match that starts in the middle of a [character](#def-g10-text-encodings-code-point).

**Solution of Exercise 5.13.**

The [encoding](#def-g10-text-encodings-encoding) of a [character](#def-g10-text-encodings-code-point) starts with a first byte, which is never a continuation byte; inside the [encoding](#def-g10-text-encodings-encoding) of a longer [character](#def-g10-text-encodings-code-point), every byte after the first is a continuation byte. So a match could only start at the first byte of the longer [character](#def-g10-text-encodings-code-point), and then the two first bytes are equal; but the first byte gives the length, so the two [characters](#def-g10-text-encodings-code-point) would have the same length, a contradiction. A word is a sequence of [characters](#def-g10-text-encodings-code-point), so its bytes start with a first byte: a match of the word in the text always starts at the first byte of a [character](#def-g10-text-encodings-code-point) of the text, never in its middle.

**Exercise 5.14 ★★★.**

Write `fix_mojibake(s)`, which undoes one layer of [UTF-8](#def-g10-text-encodings-utf8) read as Latin-1 when that is possible and returns `s` unchanged otherwise. Why is `fix_mojibake("Café")` equal to *Café*?

**Solution of Exercise 5.14.**

`try: return s.encode("latin-1").decode("utf-8")`, and if either step raises an error, `return s` (`exercises/fix_mojibake.py`). *Café* encodes in Latin-1 to `43 61 66 E9`, which is not valid [UTF-8](#def-g10-text-encodings-utf8) (`E9` is not followed by continuation bytes): decoding fails, and the string is returned unchanged. A correct string is left alone, and a string garbled once is repaired.

**Exercise 5.15 ★★★.**

A text has $10{,}000$ [characters](#def-g10-text-encodings-code-point): $9{,}000$ [ASCII](#def-g10-text-encodings-ascii) [characters](#def-g10-text-encodings-code-point), $900$ accented Latin letters and $100$ euro signs. Give its size in bytes in [UTF-8](#def-g10-text-encodings-utf8), in UTF-16 and in a one-byte table that has all these [characters](#def-g10-text-encodings-code-point). When would UTF-16 be the smaller of the first two?

**Solution of Exercise 5.15.**

[UTF-8](#def-g10-text-encodings-utf8): $9000 \times 1 + 900 \times 2 + 100 \times 3 = 11{,}100$ bytes. UTF-16: $10{,}000 \times 2 = 20{,}000$ bytes. A one-byte table: $10{,}000$ bytes. UTF-16 is smaller than [UTF-8](#def-g10-text-encodings-utf8) when most [characters](#def-g10-text-encodings-code-point) lie from `U+0800` to `U+FFFF`, where [UTF-8](#def-g10-text-encodings-utf8) needs $3$ bytes and UTF-16 $2$: Chinese, Japanese or Korean text, for example.

## 5.7 Problem: The Notice Board

**Problem 5.1.**

Weekend problem — what the station screen shows

The station’s notice board receives the café’s message as a file of bytes. The program `exercises/notice_board.py` prints the bytes of the message, garbles it once and twice, and counts the bytes of the town’s place names in three [encodings](#def-g10-text-encodings-encoding).

**Part I — A byte dump.**

1. The file begins `4c 69 67 68 74 68 6f 75 73 65 20 43 61 66 c3 a9` . Using the [ASCII](#def-g10-text-encodings-ascii) table, decode the first $14$ bytes.
2. Which bytes are not [ASCII](#def-g10-text-encodings-ascii) ? Using the [UTF-8](#def-g10-text-encodings-utf8) patterns, decode them to one [code point](#def-g10-text-encodings-code-point) and name the [character](#def-g10-text-encodings-code-point) .
3. The second line of the dump is `3a 20 63 72 c3 aa 70 65 73 20 74 6f 64 61 79` . Decode it.
4. How many [characters](#def-g10-text-encodings-code-point) and how many bytes does the whole message have?

**Part II — Which encoding?**

5. Could these bytes be Latin-1? What would the board show then?
6. Could they be pure [ASCII](#def-g10-text-encodings-ascii) ? Why not?
7. Explain why a valid [UTF-8](#def-g10-text-encodings-utf8) reading is strong evidence that the file is [UTF-8](#def-g10-text-encodings-utf8) : what would a Latin-1 text have to contain for its bytes to be valid [UTF-8](#def-g10-text-encodings-utf8) by chance?
8. The board shows *Lighthouse CafÃ©: crÃªpes today* . Which [encoding](#def-g10-text-encodings-encoding) did the board use, and which item of the method does this match?

**Part III — Two layers.**

9. A second, older screen copies the garbled text, saves it in [UTF-8](#def-g10-text-encodings-utf8) , and reads it back as Latin-1. Using the program’s output, how is *é* written after two layers? Give the four [code points](#def-g10-text-encodings-code-point) .
10. How many bytes does *é* take in [UTF-8](#def-g10-text-encodings-utf8) after one layer, and after two?
11. Show that each layer at least doubles the number of bytes of every [non-ASCII](#def-g10-text-encodings-ascii) [character](#def-g10-text-encodings-code-point) .
12. Undo the two layers in Python with the function `ungarble` of the program, and say in which order the two operations are applied at each step.
13. What happens to the [ASCII](#def-g10-text-encodings-ascii) [characters](#def-g10-text-encodings-code-point) of the message through the layers, and why?

**Part IV — The town’s names.**

14. The town has $30$ places. How many bytes do their names take in [UTF-8](#def-g10-text-encodings-utf8) , in UTF-16 and in Latin-1, according to the program?
15. Explain why the UTF-16 total is exactly twice the number of [characters](#def-g10-text-encodings-code-point) .
16. Explain why the [UTF-8](#def-g10-text-encodings-utf8) total is one more than the Latin-1 total.
17. How many bytes does [UTF-8](#def-g10-text-encodings-utf8) save over UTF-16 on these names, and what fraction is that?
18. If the café were renamed with a Greek word of $6$ letters (each Greek letter has a [code point](#def-g10-text-encodings-code-point) between `U+0370` and `U+03FF` ), how would each total change?
19. State the result: the sizes of the town’s names in the three [encodings](#def-g10-text-encodings-encoding) , the saving of [UTF-8](#def-g10-text-encodings-utf8) over UTF-16, and the rule that turns *é* into *Ã©* .

**Solution of Problem 5.1.**

**1.** *Lighthouse Caf*: `4c` is *L*, `69` *i*, …, `20` the space, `43` *C*, `61` *a*, `66` *f*.

**2.** `c3 a9`. `C3` begins a two-byte [character](#def-g10-text-encodings-code-point); the free bits `00011` and `101001` give `U+00E9`, *é*.

**3.** *: crêpes today*, with `c3 aa` for *ê* (`U+00EA`).

**4.** *Lighthouse Café: crêpes today* has $29$ [characters](#def-g10-text-encodings-code-point) and $16 + 15 = 31$ bytes: two [characters](#def-g10-text-encodings-code-point) take two bytes.

**5.** Every byte is a Latin-1 [character](#def-g10-text-encodings-code-point), so yes: the board would show *Lighthouse CafÃ©: crÃªpes today*.

**6.** Bytes `c3`, `a9` and `aa` are above `7f`; [ASCII](#def-g10-text-encodings-ascii) has only $128$ codes.

**7.** For a Latin-1 text to be valid [UTF-8](#def-g10-text-encodings-utf8) by chance, every byte from `C2` to `F4`, that is, most accented letters, capital or small, would have to be followed by exactly the right number of bytes from `80` to `BF`, which are symbols such as *©* or *«*. Real texts almost never contain such pairs, so valid [UTF-8](#def-g10-text-encodings-utf8) with [non-ASCII](#def-g10-text-encodings-ascii) bytes is almost certainly [UTF-8](#def-g10-text-encodings-utf8).

**8.** The board decoded with Latin-1 (or a close one-byte table): item 1 of the method.

**9.** The program prints `\xc3\x83\xc2\xa9` for *é*: the four [code points](#def-g10-text-encodings-code-point) `U+00C3`, `U+0083`, `U+00C2`, `U+00A9`.

**10.** After one layer *é* is two [characters](#def-g10-text-encodings-code-point), *Ã* and *©*, of two [UTF-8](#def-g10-text-encodings-utf8) bytes each: $4$ bytes. After two layers it is four [characters](#def-g10-text-encodings-code-point) of two bytes each: $8$ bytes.

**11.** A [non-ASCII](#def-g10-text-encodings-ascii) [character](#def-g10-text-encodings-code-point) takes at least $2$ [UTF-8](#def-g10-text-encodings-utf8) bytes, all of them $128$ or more. Read as Latin-1, each of these bytes becomes one [non-ASCII](#def-g10-text-encodings-ascii) [character](#def-g10-text-encodings-code-point), which in turn takes $2$ [UTF-8](#def-g10-text-encodings-utf8) bytes. So a [character](#def-g10-text-encodings-code-point) of $k \ge 2$ bytes becomes $k$ [characters](#def-g10-text-encodings-code-point) of $2$ bytes, $2k$ bytes.

**12.** At each step, first encode with Latin-1 (which gives back the bytes that were mis-read), then decode with [UTF-8](#def-g10-text-encodings-utf8); the step is applied twice, undoing the last layer first.

**13.** They pass unchanged: an [ASCII](#def-g10-text-encodings-ascii) [character](#def-g10-text-encodings-code-point) is one byte below $128$ in [UTF-8](#def-g10-text-encodings-utf8), and that byte is the same [character](#def-g10-text-encodings-code-point) in Latin-1.

**14.** $301$ bytes in [UTF-8](#def-g10-text-encodings-utf8), $600$ in UTF-16 and $300$ in Latin-1.

**15.** All $300$ [characters](#def-g10-text-encodings-code-point) of the names have [code points](#def-g10-text-encodings-code-point) below `U+10000`, and UTF-16 writes each of them in two bytes: $2 \times 300 = 600$.

**16.** Every [character](#def-g10-text-encodings-code-point) takes one byte in Latin-1. In [UTF-8](#def-g10-text-encodings-utf8) the same holds for [ASCII](#def-g10-text-encodings-ascii) [characters](#def-g10-text-encodings-code-point), and only *é*, in *Lighthouse Café*, takes two.

**17.** $600 - 301 = 299$ bytes, very nearly half ($299/600 \approx 49.8\,\%$).

**18.** The name *Lighthouse Café* ($15$ [characters](#def-g10-text-encodings-code-point), $16$ bytes in [UTF-8](#def-g10-text-encodings-utf8)) is replaced by $6$ Greek letters of $2$ bytes each in [UTF-8](#def-g10-text-encodings-utf8) and in UTF-16. [UTF-8](#def-g10-text-encodings-utf8): $301 - 16 + 12 = 297$ bytes. UTF-16: $600 - 30 + 12 = 582$ bytes. Latin-1 has no Greek letters: the names could no longer be written in it at all.

**19.** The town’s $30$ place names take $301$ bytes in [UTF-8](#def-g10-text-encodings-utf8), $600$ in UTF-16 and $300$ in Latin-1: [UTF-8](#def-g10-text-encodings-utf8) saves $299$ bytes over UTF-16, almost half. The rule of the notice board: [UTF-8](#def-g10-text-encodings-utf8) bytes read as Latin-1 turn every [non-ASCII](#def-g10-text-encodings-ascii) letter into two [characters](#def-g10-text-encodings-code-point), and *é*, bytes `C3 A9`, becomes *Ã©*.
