- In mathematics, negative numbers in any base are represented by prefixing them with a minus sign (“−”). However, in computer hardware, numbers are represented only as sequences of bits, without extra symbols.
- Two’s complement is one of the method to represent signed numbers using binary numeral system, which uses only two symbols: typically “0” (zero) and “1” (one).
- Negative numbers are written with a leading one instead of a leading zero.
- Invert and add one: negating a number (whether negative or positive) is done by inverting or complementing all the bits (switched from “1” to “0” or “0 “to “1”) and then adding one to that result. See this post for why inversion and adding one works
- -x → invert(x) + 1
- OR Invert the result of the number minus one
- -x → invert(x-1)
Examples
binary number in double quote
-1 → invert(1) + "1" → invert("00000001") + "1" → "11111110" + "1" → "11111111"
OR
-1 → invert(1-1) → invert(0) → invert("00000000") → "11111111"
-8 → invert(8) + "1" → invert("00001000") + "1" → "11110111" + "1" → "11111000"
OR
-8 → invert(8-1) → invert(7) → invert("00000111") → "11111000"
-128 → invert(128) + "1" → invert("1000000") + "1" → "01111111" + "1" → "10000000"
OR
-128 → invert(128-1) → invert(127) → invert("01111111") → "10000000"
Eight-bit two’s complement
BINARY VALUE | TWO’S COMPLEMENT INTERPRETATION | UNSIGNED INTERPRETATION |
---|---|---|
0000 0000 | 0 | 0 |
0000 0001 | 1 | 1 |
0000 0010 | 2 | 2 |
0000 0011 | 3 | 3 |
0000 0100 | 4 | 4 |
0000 0101 | 5 | 5 |
0000 0110 | 6 | 6 |
0000 0111 | 7 | 7 |
0000 1000 | 8 | 8 |
⋮ | ⋮ | ⋮ |
0111 1110 | 126 | 126 |
0111 1111 | 127 | 127 |
1000 0000 | −128 | 128 |
1000 0001 | −127 | 129 |
1000 0010 | −126 | 130 |
⋮ | ⋮ | ⋮ |
1111 0111 | -9 | 247 |
1111 1000 | -8 | 248 |
1111 1001 | -7 | 249 |
1111 1010 | -6 | 250 |
1111 1011 | -5 | 251 |
1111 1100 | -4 | 252 |
1111 1101 | -3 | 253 |
1111 1110 | −2 | 254 |
1111 1111 | −1 | 255 |