Two's Complement
Two's complement is the standard way to store signed integers, giving one zero and uniform arithmetic.
The representation
In two's complement the most significant bit has a negative weight of −2ⁿ⁻¹ while the rest keep their normal positive weights. So 8-bit 11111111 equals −128 + 127 = −1, and 10000000 equals −128.
Negating a number
To negate a value, invert every bit and add 1. Negating 8-bit 00000101 (5) gives 11111010 + 1 = 11111011, which reads as −5. Applying the same procedure again returns the original.
Why addition just works
Because negatives are stored modulo 2ⁿ, a subtraction a−b becomes the addition a + (−b) with the same adder used for unsigned numbers. The carry out of the top bit is simply discarded.
Range and asymmetry
With n bits the range is −2ⁿ⁻¹ to 2ⁿ⁻¹−1. The most negative value has no positive counterpart, so negating it overflows back to itself — a subtle edge case worth guarding in code.
Overflow detection
Signed overflow occurs when two operands of the same sign produce a result of the opposite sign. Hardware flags this by comparing the carry into and out of the sign bit.
| Bits (8-bit) | Value |
|---|---|
| 00000000 | 0 |
| 01111111 | 127 |
| 10000000 | -128 |
| 11111111 | -1 |
def neg(x, n):
return (~x + 1) & ((1 << n) - 1)
print(neg(5, 8)) # 251 = -5 pattern