Two's Complement

The problem

A computer stores numbers as bits. There is no minus sign in hardware. Signed-magnitude uses the leftmost bit as the sign and the rest as the value, but it has two zeros (0000 and 1000) and needs separate circuits for addition and subtraction. Two's complement avoids both.

The number wheel

Two wheels below. Left is 1-digit decimal (ten's complement). Right is 4-bit binary (two's complement). Same idea, different bases.

Both wheels start at 4 (marked with the green ring) and compute 4 − 3 = 1. On each wheel, the two buttons take different paths but land at the same place.

Decimal · 10 positions

Range −5 to +4
4 position: 4 Start at 4.

Binary · 16 positions

Range −8 to +7
4 position: 0100 Start at 4.
Same destination. Both wheels land on 1. Going backward 3 steps and going forward (positions − 3) steps end at the same place because the wheel wraps. On the decimal wheel, 7 is 10 − 3. On the binary wheel, 1101 (13) is 16 − 3. Those are the ten's and two's complements of 3. Adding a complement gives the same result as subtracting the original, so hardware can drop subtraction circuits entirely and always add.

The formula

For k bits:

Negative(I) = 2k − I
Example.
−3 in 4 bits: 16 − 3 = 13 = 1101.
−6 in 4 bits: 16 − 6 = 10 = 1010.

Shortcut: flip and add 1

For large k, computing 2k − I is slow. The mechanical version:

  1. Write the positive number in binary.
  2. Flip every bit (0 becomes 1, 1 becomes 0).
  3. Add 1.
Example. Find −5 in 4 bits.
+5 = 0101. Flip to 1010. Add 1 to get 1011.
Check: 16 − 5 = 11 = 1011. ✓

Reading a two's complement number

Example. What is 1100?
Leftmost is 1, so negative. Flip to 0011, add 1 to get 0100 = 4.
So 1100 = −4.

Range

With k bits:

−2k−1 to 2k−1 − 1

4 bits: −8 to +7. 8 bits: −128 to +127. 32 bits: about ±2.1 billion.

Full 4-bit table

BinarySigned value

The odd one: 1000

In 4 bits, 1000 is −8, but there is no +8 (the largest positive is +7). Applying the shortcut to 1000: flip to 0111, add 1, back to 1000. Negating the most negative value returns itself.

Try it

All four use 4-bit two's complement. Binary answers are exactly 4 digits.

1. Write −5 in 4-bit two's complement.

2. The pattern 1010 is which decimal value?

3. Compute 6 + (−4) in 4-bit two's complement.

4. Compute 0111 + 0001 in 4 bits.

Takeaways