Understanding Two's Complement
Two's complement is the most common method for representing signed integers in binary. It is used by virtually all modern computers because it simplifies the design of arithmetic circuits -- the same hardware that adds unsigned numbers can also add signed numbers in two's complement form.
How Two's Complement Works
Positive Numbers
Positive numbers are represented the same as in unsigned binary, with the most significant bit (MSB) being 0.
+5 (8-bit) = 00000101
Negative Numbers
Invert all bits of the absolute value (one's complement), then add 1 to get two's complement.
-5: 00000101 -> 11111010 -> 11111011
Range
For n bits, the range is from -2^(n-1) to 2^(n-1) - 1.
8-bit: -128 to +127
Conversion Steps
- If the number is positive, simply convert it to binary and pad with leading zeros.
- If the number is negative, first convert the absolute value to binary.
- Flip all the bits (0 becomes 1, 1 becomes 0) -- this gives the one's complement.
- Add 1 to the one's complement -- this gives the two's complement.
Why Two's Complement?
- There is only one representation for zero (unlike one's complement).
- Addition and subtraction use the same circuitry.
- The MSB naturally indicates the sign (0 = positive, 1 = negative).