Skip to content
Book 1: Theory Fundamentals

Book 1 · Chapter 1

Information representation

§1.1§1.2§1.3Banker · ≈ 20.1 m · →B1·1

This chapter is in the ebook.

Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.

Open in the ebook

§1.1 Data representation · Binary arithmetic

Short code B1·1·1

§1.2 Multimedia

Short code B1·1·2

§1.3 Compression

Short code B1·1·3

Binary prefixes: kibi or kilo?

Short code B1·1·10

pairs = [("kilo", "kibi"), ("mega", "mebi"),
         ("giga", "gibi"), ("tera", "tebi")]
for n, (dec, bin_) in enumerate(pairs, start=1):
    d = 1000 ** n
    b = 1024 ** n
    gap = (b - d) / d * 100
    print(f"{dec}: {d:,}  {bin_}: {b:,}  (+{gap:.1f}%)")
Each decimal prefix beside its binary twin. Notice that the gap grows with every step: 2.4 % at kilo, about 10 % at tera.

Output

kilo: 1,000  kibi: 1,024  (+2.4%)
mega: 1,000,000  mebi: 1,048,576  (+4.9%)
giga: 1,000,000,000  gibi: 1,073,741,824  (+7.4%)
tera: 1,000,000,000,000  tebi: 1,099,511,627,776  (+10.0%)
Run and checked before printing
drive = 2 * 1000 ** 4     # "2 TB" box
print(f"{drive:,} bytes")
print(f"{drive / 1024 ** 4:.2f} TiB")
The archive drive is sold as 2 TB. The operating system counts in binary units, so it reports fewer TiB. Nothing is missing.

Output

2,000,000,000,000 bytes
1.82 TiB
Run and checked before printing

Number bases: binary, denary and hexadecimal

Short code B1·1·11

DECLARE Number : INTEGER
DECLARE Bits : STRING
Number ← 181
Bits ← ""
WHILE Number > 0
   IF Number MOD 2 = 1 THEN
      Bits ← "1" & Bits
   ELSE
      Bits ← "0" & Bits
   ENDIF
   Number ← Number DIV 2
ENDWHILE
OUTPUT Bits
Denary to binary by repeated division. Each pass puts the remainder (0 or 1) on the left of the string, so the bits come out in the right order.

Output

10110101
Run and checked before printing
DECLARE Number : INTEGER
DECLARE Remainder : INTEGER
DECLARE Hex : STRING
DECLARE Digits : STRING
Digits ← "0123456789ABCDEF"
Number ← 967
Hex ← ""
WHILE Number > 0
   Remainder ← Number MOD 16
   Hex ← MID(Digits, Remainder + 1, 1) & Hex
   Number ← Number DIV 16
ENDWHILE
OUTPUT Hex
The same idea in base 16. MID picks the hexadecimal digit for each remainder out of Digits, the string of all sixteen digits.

Output

3C7
Run and checked before printing

Binary Coded Decimal

Short code B1·1·12

n = 181
print("binary ", format(n, "08b"))
print("hex    ", format(n, "X"))
print("BCD    ", " ".join(format(int(d), "04b") for d in str(n)))
181 in every form this chapter uses. BCD codes each denary digit in its own four bits, so it needs 12 bits where binary needs 8.

Output

binary  10110101
hex     B5
BCD     0001 1000 0001
Run and checked before printing

Negative numbers: one's and two's complement

Short code B1·1·13

def read_twos(bits):
    value = int(bits, 2)
    if bits[0] == "1":
        value = value - 256
    return value

def write_twos(n):
    return format(n % 256, "08b")

print(read_twos("10110110"))
print(write_twos(-74))
print(read_twos("01111111"))
print(read_twos("10000000"))
Reading and writing 8-bit two's complement. The leftmost bit is worth −128, so a pattern that starts with 1 is negative.

Output

-74
10110110
127
-128
Run and checked before printing
plus = format(74, "08b")
ones = "".join("1" if b == "0" else "0" for b in plus)
twos = format(int(ones, 2) + 1, "08b")
print("+74              ", plus)
print("one's complement ", ones)
print("two's complement ", twos)
One's complement flips every bit of +74. Two's complement adds 1 to that. Only the second is −74 in two's complement.

Output

+74               01001010
one's complement  10110101
two's complement  10110110
Run and checked before printing

Binary addition and overflow

Short code B1·1·14

a = 0b10110110          # 182
b = 0b01100111          # 103
total = a + b
print(format(total, "09b"), "=", total)
low8 = total & 0xFF     # keep 8 bits
print("8-bit result:", format(low8, "08b"))
print("overflow:", total > 255)
Adding two unsigned 8-bit numbers. The true total needs a ninth bit, so an 8-bit register overflows.

Output

100011101 = 285
8-bit result: 00011101
overflow: True
Run and checked before printing

Binary subtraction

Short code B1·1·15

a = 0b01011100              # 92
b = 0b00110101              # 53
neg_b = (~b + 1) & 0xFF     # -53
raw = a + neg_b
ans = raw & 0xFF            # drop bit 9
print("-53   ", format(neg_b, "08b"))
print("sum   ", format(raw, "09b"))
print("answer", format(ans, "08b"), "=", ans)
The Mark Ladder's subtraction, run: 92 − 53 done by adding the two's complement of 53.

Output

-53    11001011
sum    100100111
answer 00100111 = 39
Run and checked before printing

Where hexadecimal and BCD earn their place

Short code B1·1·16

count = 2047
for digit in str(count):
    print(digit, "->", format(int(digit), "04b"))
print("patterns never used:", [format(v, "04b") for v in range(10, 16)])
A ticket counter keeps the visitor count in BCD: one nibble per display digit, so each digit goes straight to its own display.

Output

2 -> 0010
0 -> 0000
4 -> 0100
7 -> 0111
patterns never used: ['1010', '1011', '1100', '1101', '1110', '1111']
Run and checked before printing

Characters in binary: ASCII, extended ASCII and Unicode

Short code B1·1·17

for ch in ["A", "B", "Z", "a", "0", " "]:
    code = ord(ch)
    print(repr(ch), code, format(code, "07b"))
Character codes are in order: B follows A, and every lower-case letter is exactly 32 after its capital. You are never asked to memorise them. You only use a code you are given.

Output

'A' 65 1000001
'B' 66 1000010
'Z' 90 1011010
'a' 97 1100001
'0' 48 0110000
' ' 32 0100000
Run and checked before printing
letters = ["A", "\u00e9", "\u0628", "\u20ac"]
for ch in letters:
    n = ord(ch)
    print(f"U+{n:04X}", n, n.bit_length())
Unicode code points, written U+ and hexadecimal, then in denary, then the number of bits each needs. The first 128 match ASCII; the rest reach every script. (The characters are written as escapes so the code prints in any font.)

Output

U+0041 65 7
U+00E9 233 8
U+0628 1576 11
U+20AC 8364 14
Run and checked before printing

Bitmap images: pixels, resolution and colour depth

Short code B1·1·18

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

How big is a bitmap?

Short code B1·1·19

width, height, depth = 1024, 768, 16
bits = width * height * depth
size_bytes = bits // 8
print(bits, "bits")
print(size_bytes, "bytes")
print(size_bytes // 1024, "KiB")
print(768 * 2, "KiB (cancelled by hand)")
The Mark Ladder's calculation, run. Width × height gives the pixels; × colour depth gives bits; ÷ 8 gives bytes; ÷ 1024 gives KiB. On paper you cancel first: the 1024s cancel and 16 ÷ 8 = 2, leaving 768 × 2.

Output

12582912 bits
1572864 bytes
1536 KiB
1536 KiB (cancelled by hand)
Run and checked before printing

Changing resolution and colour depth

Short code B1·1·20

def mib(w, h, depth):
    return w * h * depth / 8 / 1024 ** 2

print(round(mib(4000, 3000, 24), 2), "MiB")
print(round(mib(2000, 1500, 24), 2), "MiB")
print(round(mib(4000, 3000, 8), 2), "MiB")
print(2 ** 24, "colours vs", 2 ** 8)
One scan, three versions: the original, half the width and height, and 8-bit colour. Halving both dimensions quarters the file; cutting the colour depth from 24 to 8 bits divides it by three.

Output

34.33 MiB
8.58 MiB
11.44 MiB
16777216 colours vs 256
Run and checked before printing

Vector graphics

Short code B1·1·21

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Bitmap or vector?

Short code B1·1·22

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Sound: from wave to numbers

Short code B1·1·23

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Sampling rate and sampling resolution

Short code B1·1·24

for resolution in [2, 4, 8, 16]:
    print(f"{resolution:>2} bits: {2 ** resolution:,} levels")
How many levels each sample can choose from. Every extra bit doubles them.

Output

 2 bits: 4 levels
 4 bits: 16 levels
 8 bits: 256 levels
16 bits: 65,536 levels
Run and checked before printing

How big is a sound file?

Short code B1·1·25

rate = 44_100        # samples per second
resolution = 16      # bits per sample
seconds = 60
bits = rate * resolution * seconds
print(bits, "bits")
print(bits // 8, "bytes")
print(f"{bits / 8 / 1024 ** 2:.2f} MiB")
A one-minute mono track at CD-style settings. A computer does this sum for you; in the exam the numbers are chosen so that they cancel.

Output

42336000 bits
5292000 bytes
5.05 MiB
Run and checked before printing
rate = 32 * 1000        # 32 kHz in Hz
resolution = 16         # bits per sample
seconds = 2 * 60        # 2 minutes
bits = rate * resolution * seconds
print(bits, "bits")
print(bits // 8, "bytes")
print(bits / 8 / 1000 / 1000, "MB")
The sound Mark Ladder's calculation, run: kHz becomes Hz, minutes become seconds, then ÷ 8 and ÷ 1000 twice for MB.

Output

61440000 bits
7680000 bytes
7.68 MB
Run and checked before printing

Why compress? Lossy and lossless

Short code B1·1·26

Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.

Run-length encoding and compressing each kind of file

Short code B1·1·27

row = "WWWWWWBBBWWWWRRRRRRR"
runs = []
for colour in row:
    if runs and runs[-1][1] == colour:
        runs[-1][0] += 1
    else:
        runs.append([1, colour])
print(runs)
print(len(row), "pixels,", len(runs), "runs")
Run-length encoding of one row of a bitmap: each run of identical, adjacent pixels becomes a (count, colour) pair.

Output

[[6, 'W'], [3, 'B'], [4, 'W'], [7, 'R']]
20 pixels, 4 runs
Run and checked before printing
row = "WBWBWBWB"
runs = []
for colour in row:
    if runs and runs[-1][1] == colour:
        runs[-1][0] += 1
    else:
        runs.append([1, colour])
print(len(row), "values before")
print(2 * len(runs), "values after")
When nothing repeats, RLE makes the data bigger: every single pixel now needs a count as well as a colour.

Output

8 values before
16 values after
Run and checked before printing

Workbook 1: Information representation

Short code W1·1 · Theory Fundamentals Workbook

The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.

Ask Z about Information representation
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook