Two's Complement
Convert a signed integer to two’s-complement binary, and back.
Range for 8 bits: -128 to 127.
−5 in 8-bit two’s complement is 11111011. To encode a negative number, take the binary of its magnitude (5 = 00000101), flip every bit (11111010), then add 1 (11111011). To decode, if the leading bit is 1 the value is negative: read it as unsigned (251) and subtract 2⁸ (256), giving −5.
What two’s complement is
Two’s complement is the standard way computers store signed integers. A fixed number of bits (the width) represents a range that straddles zero. The most significant bit acts as a sign bit: 0 marks a non-negative value, 1 a negative one. Non-negative numbers are written in ordinary binary; a negative number −n is stored as 2ⁿ⁽ᵇⁱᵗˢ⁾ minus its magnitude, which is the same as flipping the bits of the magnitude and adding 1.
Encoding: take n modulo 2^bits, then write the result in binary.
The flip-and-add-one shortcut
For a negative number you do not have to compute the modulus by hand. Write the magnitude in binary, invert every bit (0 → 1, 1 → 0), then add 1. The two methods always agree because inverting all bits subtracts the value from 2ⁿ⁽ᵇⁱᵗˢ⁾ − 1, and adding 1 lands on 2ⁿ⁽ᵇⁱᵗˢ⁾ − magnitude.
- 1 Pick a bit width. For −5 use 8 bits. The range a signed 8-bit integer holds is −128 to 127, so −5 fits.
- 2 Write the magnitude in binary. |−5| = 5 = 00000101, padded to 8 bits.
- 3 Invert every bit. 00000101 becomes 11111010.
- 4 Add 1. 11111010 + 1 = 11111011 — that is −5 in 8-bit two’s complement.
- 5 Verify with the modulus rule. −5 mod 256 = 251, and 251 in binary is 11111011. They match.
Signed range by bit width
A b-bit signed integer holds −2^(b−1) to 2^(b−1) − 1.
| Bit width | Minimum | Maximum | Example: −5 |
|---|---|---|---|
| 4 | −8 | 7 | 1011 |
| 8 | −128 | 127 | 11111011 |
| 16 | −32768 | 32767 | 1111111111111011 |
| 32 | −2147483648 | 2147483647 | 11111111111111111111111111111011 |
Why two’s complement won
Two’s complement has a single representation of zero (all bits 0), unlike sign-and-magnitude or one’s complement, which both have a separate −0. It also lets the same adder hardware handle signed and unsigned addition: you add the bit patterns and discard any carry out of the top bit. The cost is asymmetry — the most negative value (−2ⁿ⁽ᵇⁱᵗˢ⁾⁻¹) has no positive counterpart, so negating it overflows. Overflow happens whenever the true result falls outside the width’s range; the stored bits silently wrap around the modulus.