Proof Academy · Python · Journey 10

Binary and text encoding

Trace place values, detect overflow and distinguish characters from stored bytes.

Lab and core lesson: 40–50 minutes, plus guided study · Builds on Files, CSV and persistent data

01 · Understand and predict

Interpret bits using a representation

Bits have place values in binary. In an unsigned four-bit number the weights are 8, 4, 2 and 1. For 1011, add 8 + 0 + 2 + 1 to get 11. You can also scan left to right, doubling the total and adding the new bit each time.

An unsigned byte holds values 0–255. Adding 1 to 255 requires nine bits, so a calculation restricted to eight bits overflows. Python integers normally grow to fit, so a Python sum can exceed 255. In eight-bit two’s complement, the leftmost weight is −128. For example 11111111 represents −1 in that format.

An encoding maps characters to numeric codes. ASCII uses 7 bits and maps A to 65. Unicode assigns code points to a much larger set of characters. UTF-8 represents those code points as bytes. Some characters take more than one byte.

total = 0
for bit in "1011":
    total = total * 2 + int(bit)
print(total)

Worked trace

  1. Read 1. Double 0 and add 1 to get 1.
  2. Read 0. Double 1 and add 0 to get 2.
  3. Read 1. Double 2 and add 1 to get 5.
  4. Read 1. Double 5 and add 1 to get 11.

Count characters and bytes separately

Each string contains one character. UTF-8 uses one byte for A and two for £. The printed rows are 1 1 and 1 2.

for text in ["A", "£"]:
    print(len(text), len(text.encode("utf-8")))
What does 11111111 represent as an unsigned byte?

From code to machine. Memory and storage hold bit patterns. A byte can represent a number, part of a character, or part of an instruction depending on its use. The program and processor determine how to interpret those bits.

Guided study

Read it, trace it, test it

Decide how the bits will be interpreted

The same bit pattern can mean different things. Eight 1 bits represent 255 as an unsigned byte and −1 as an eight-bit two’s complement integer. A character encoding interprets a group of bits in a different way again. Whenever a question gives a bit pattern, identify its width and representation before interpreting it. Do not infer a negative number just because the leftmost bit is 1. That bit is worth positive 128 in an unsigned byte and negative 128 in eight-bit two’s complement.

PatternUnsignedEight-bit two’s complement
0000000000
01111111127127
10000000128−128
11111111255−1

One decoding method for signed bytes is to calculate the unsigned number and subtract 256 when the first bit is 1. For 11111110, the unsigned value is 254. Subtracting 256 gives −2. This works because the leftmost contribution changes from +128 to −128, a difference of 256. The signed range is −128 to 127. Positive and negative limits are different because one pattern is used for zero.

Connect a trace to place value

Start an accumulator at zero. On reading a new bit, double the value already accumulated, then add the new bit. Doubling shifts each existing place value left by one. For 0101, the totals are 0, 1, 2, 5. Leading zeros matter when the task asks for exactly eight bits even though they do not change an unsigned numeric value. Keep the raw input as text for the length check. Converting early could lose those zeros or accept text that the format rejects.

Binary addition uses a carry when the sum in a column reaches 2. 1 + 1 gives binary 10. For 11111111 + 00000001, the carry travels through all eight positions and produces 100000000. This is 256. In a fixed-width eight-bit unsigned representation, that sum does not fit. In this exercise we report overflow explicitly. Python's normal integer operation still produces the mathematical answer because its integers are not restricted to eight bits.

Read characters, codes and bytes as separate things

The string "65" is made of two characters. It differs from the integer 65 and from the single character "A". ord("A") gives the Unicode code point 65, which agrees with ASCII for A. "A".encode("utf-8") produces one byte, while "£".encode("utf-8") uses two bytes. When a file task asks for storage size, count encoded bytes or use the stated encoding assumptions. Do not treat every character as one byte. An eight-bit quantity is a byte regardless of whether it represents a number, part of a letter or part of an instruction.

Practise a Paper 2 change request

Write a helper decode_signed(bits) that returns the signed value of a valid eight-bit pattern. Write a caller that checks the length and rejects any character outside 0 and 1, then prints the result or Invalid. Before running, plan tests for −128, −1, zero, +127, a seven-character pattern and an invalid digit. Explain why a test using only values that start with 0 cannot detect a bug that decodes everything as unsigned. Use Run with my input in a lab and supply one input line for this separate exercise.

Group bits to read hexadecimal

Each hexadecimal digit represents four bits. Split 10111110 into 1011 and 1110. Their values are 11 and 14, written B and E, so the byte is BE in hexadecimal. This is a shorter notation for the same bit pattern. Reading it as a signed byte still requires the signed interpretation rule.

Check your guided practice

Check the length and the characters before conversion. Inside the helper, start with value = int(bits, 2). If bits[0] == "1", return value - 256. Otherwise return value. Test 10000000, 11111111, 00000000 and 01111111; they should produce −128, −1, 0 and 127. The inputs 1000000 and 00000002 should print Invalid. A correct result for zero alone says nothing about the negative branch.

02 · Run and repair

Shift before adding the next bit

The starter adds the digits of the input instead of decoding a binary number. Run 1011. Change the accumulator update so each existing contribution shifts one place left before the new bit is added.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

A left shift by one position multiplies a non-negative value by 2.

03 · Build independently

Check an unsigned byte addition

Read two unsigned eight-bit binary strings on separate lines and report the decimal result or overflow.

  • Each operand must have exactly eight characters, all 0 or 1. Print Invalid if either operand fails the check.
  • Decode valid operands and add them. Print Overflow if the sum exceeds 255. Otherwise print the decimal sum.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Use a function that checks length and loops over characters. int(bits, 2) decodes base 2, or you can reuse the running-total method from the repair.

04 · Explain and transfer

Explain your reasoning

Why is a Python result of 256 correct even though it overflows an unsigned byte?

Compare your explanation

256 is the mathematical sum. It needs nine bits, so it cannot fit in eight unsigned bits. Python can allocate additional space for an integer. An eight-bit format has a fixed limit.

Independent follow-up. Write a decoder for eight-bit two’s complement. Decode as unsigned first, then subtract 256 when the first bit is 1. Test 01111111, 10000000, 11111111 and 00000000.

Original GCSE practice · Pearson Edexcel 1CP2 2.1.1–2.1.5, 2.2.1 and 6.1.2. Download your .py file to keep it after leaving the page.

Next: From Python to the processor →