Two's complement
The conceptWhy a computer stores −1 as a row of all ones
Computers store whole numbers in a fixed number of bits. Two's complement is the usual way to fit negative numbers into those bits: the top bit counts as a large negative value instead of a positive one.
In 8 bits, the top bit is worth −128 and the other seven are worth 64, 32, down to 1. So 11111111 is −128 + 127 = −1, and 10000000 is −128. The range runs from −128 to 127.
What it’s forTurns a row of n bits into the signed whole number it stands for.
value = −bₙ₋₁·2ⁿ⁻¹ + Σ bᵢ·2ⁱ (i = 0 … n−2)
- n
- number of bits, e.g. 8, 32 or 64
- bₙ₋₁
- the top bit, which carries a negative weight
- bᵢ
- each lower bit, 0 or 1
- 2ⁱ
- the place value of bit i: 1, 2, 4, 8 …
What it givesOne signed number per bit pattern, from −2ⁿ⁻¹ up to 2ⁿ⁻¹ − 1.
- 4-bit pattern 1011
- = −8 + 0 + 2 + 1
- = −5