Show contents
Chapter 2 of 7 · 20 min
Text and images
By the end of this chapter, you'll be able to
- Explain how a character becomes a number with Unicode
- Encode and decode text in UTF-8 and recognise an encoding error
- Represent an image as a grid of pixels and compute its size
- Understand the principle of a simple compression
From characters to numbers
To store text, each character is numbered. The first major standard, ASCII (1960s), numbered 128 characters: English letters without accents, digits, punctuation. Not enough for the rest of the world. Unicode now gives a unique number, the code point, to more than 150,000 characters from every script: Latin, Arabic, Chinese, N'Ko, emojis…
for c in "Aé߀ب😀":
print(c, ord(c), hex(ord(c)))
print(chr(65), chr(233))
A 65 0x41
é 233 0xe9
߀ 1984 0x7c0
ب 1576 0x628
😀 128512 0x1f600
A é
ord gives a character's code point, chr does the reverse. Code points are often written in hexadecimal, such as U+00E9 for “é”.
From numbers to bytes: UTF-8
A code point can exceed 255: it does not always fit in a byte. An encoding describes how to write it as bytes. The most widespread, by far, is UTF-8: ASCII characters take 1 byte, accented letters 2, most other scripts 2 or 3, emojis 4.
for word in ("Kofi", "Ségou", "سلام", "😀"):
data = word.encode("utf-8")
print(word, len(word), "character(s),", len(data), "bytes:", data.hex(" "))
Kofi 4 character(s), 4 bytes: 4b 6f 66 69
Ségou 5 character(s), 6 bytes: 53 c3 a9 67 6f 75
سلام 4 character(s), 8 bytes: d8 b3 d9 84 d8 a7 d9 85
😀 1 character(s), 4 bytes: f0 9f 98 80
encode turns text into bytes (bytes), decode does the reverse. “é” becomes the two bytes c3 a9. The length in characters and the size in bytes are therefore not the same thing: a 160-“character” limit in a text message, for example, depends on the encoding used.
In memory and in files, these are just 16 bits.
Text description of the animation
- You type a letter on the keyboard.
- Unicode gives it a unique number, valid all over the world.
- UTF-8 writes it on two bytes, because 233 is beyond the ASCII range (0 to 127).
- In memory and in files, these are just 16 bits.
Images: a grid of pixels
A digital image is a grid of pixels (picture elements). Each pixel has a colour, often encoded by three intensities, red, green and blue (RGB), from 0 to 255 each: 3 bytes per pixel.
ORANGE, WHITE = (255, 136, 0), (255, 255, 255)
image = [
[WHITE, ORANGE, WHITE],
[ORANGE, ORANGE, ORANGE],
[WHITE, ORANGE, WHITE],
]
for row in image:
print("".join("█" if px == ORANGE else "·" for px in row))
width, height = 1920, 1080
print(f"Uncompressed Full HD photo: {width * height * 3 / 1_000_000:.1f} MB")
·█·
███
·█·
Uncompressed Full HD photo: 6.2 MB
A Full HD photo would weigh more than 6 MB without compression. Image formats reduce this size. Some (PNG) do it losslessly, by spotting repetitions. Others (JPEG, WebP, AVIF) do it with loss, by removing details the eye barely sees: this is why a photo of a few megapixels often weighs only a few hundred kilobytes.
Mini-lab: bytes and lettersPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: compress a row of pixels
Run-length encoding replaces a sequence of identical values with the value and its number of repetitions. Write compress(pixels) that turns ["W", "W", "W", "O", "O", "W"] into [("W", 3), ("O", 2), ("W", 1)], then decompress that does the reverse. Check that the round trip gives back the original row.
Hint 1
Hint 2
[value] * count creates a list of count times value.Show the solution and common mistakes
def compress(pixels):
runs = []
for p in pixels:
if runs and runs[-1][0] == p:
runs[-1] = (p, runs[-1][1] + 1)
else:
runs.append((p, 1))
return runs
def decompress(runs):
pixels = []
for value, count in runs:
pixels += [value] * count
return pixels
row = ["W", "W", "W", "O", "O", "W"]
runs = compress(row)
print(runs)
print(decompress(runs) == row)
print(compress(["W", "O", "W", "O"]))
[('W', 3), ('O', 2), ('W', 1)]
True
[('W', 1), ('O', 1), ('W', 1), ('O', 1)]
Run-length encoding is very efficient on large plain areas (a logo, a diagram), but it enlarges the data when everything changes at every pixel, as the last example shows: 4 values become 4 pairs. No lossless compression reduces every file: it bets on repetitions.
Common mistakes:
- Forgetting the last run: if a run is only recorded when the value changes, the last one is never added. The solution above avoids this by updating the current run.
- Testing
runs[-1]on an empty list:runs and …first checks there is at least one run.
Summary
- 1Unicode gives a unique number (code point) to every character of every script.
- 2UTF-8 writes these numbers on 1 to 4 bytes; the length in characters differs from the size in bytes.
- 3Decoding with the wrong encoding produces “é”: use UTF-8 everywhere, explicitly.
- 4An image is a grid of pixels, often 3 bytes (red, green, blue) per pixel.
- 5Lossless compression exploits repetitions; lossy compression removes barely visible details.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.