Computer Architecture Lab (Advanced)

Lesson 2 of 5

Two's Complement, Overflow and Binary Shifts

Represent negative numbers the way hardware really does, and work out exactly when arithmetic silently breaks.

🔴 Advanced 130 XP

Learn it

Computers have no minus sign — only bits. Two's complement is the trick that lets the same adder circuit handle both positive and negative numbers.

To negate a number: flip every bit, then add 1. That's it.

Because a byte only has 256 slots, adding two big numbers can wrap around past the end. That's overflow, and it has caused real rockets to explode.

Key terms

Two's complement
Signed binary representation where negating a value means inverting all bits and adding one.
Overflow
A result that cannot be represented in the available number of bits, causing a wrap-around.
Arithmetic shift
A shift that preserves the sign bit, used for multiplying or dividing signed values by powers of two.
MSB
Most significant bit — in two's complement it carries a negative weight and acts as the sign bit.

Encode −45 in 8-bit two's complement

  1. 11. Positive form: 45 = 00101101.
  2. 22. Invert: Flip every bit: 11010010.
  3. 33. Add one: 11010010 + 1 = 11010011.
  4. 44. Check: −128 + 64 + 16 + 2 + 1 = −45. Correct.

Watching a byte overflow in Python

pythondef as_int8(value):
    value &= 0xFF                 # keep only 8 bits
    return value - 256 if value & 0x80 else value

a, b = 100, 50
print(a + b)                       # 150 - fine for Python
print(as_int8(a + b))              # -106 - overflow in a signed byte!

print(as_int8(-128 >> 1 & 0xFF))   # arithmetic vs logical shift matters

100 + 50 = 150, which needs 8 bits unsigned but overflows the signed range of −128..127, wrapping to −106.

Try it

An 8-bit signed register holds 01111111. The CPU adds 1. What happens?

text  01111111   (+127)
+ 00000001   (+1)
-----------
  ????????

Challenge

Design a 6-question 'overflow detective' worksheet: for each of 6 additions of 8-bit signed values, state the binary result, the signed value, and whether the carry flag, the overflow flag, both or neither are set.

Pick whichever way suits you — every mode earns the same bonus XP.

Write at least 40 more characters to submit.

Mark your own work

Guided walkthrough — 0/5 clues revealed

  1. Clue 1 locked — reveal it only if you get stuck.
  2. Clue 2 locked — reveal it only if you get stuck.
  3. Clue 3 locked — reveal it only if you get stuck.
  4. Clue 4 locked — reveal it only if you get stuck.
  5. Clue 5 locked — reveal it only if you get stuck.

Each clue costs 7 XP (never below 33 XP). You'd earn 65 XP right now.

Extension: Repeat the exercise treating the same bit patterns as unsigned. Which answers change and why?

Quiz time

Question 1 of 4Score 0

What is the 8-bit two's complement representation of −1?