-
Notifications
You must be signed in to change notification settings - Fork 0
Two's Complement
Digital systems store data in binary form. As bits only have two states each they cannot take negative values. To represent signed numbers we need an encoding that maps certain values to the negative numbers.
A straight forward solution is to use the first bit to decide the sign. In an N bit system this leaves N-1 bits for the magnitude of the number covering 2^(N-1) to -2^(N-1). E.g. a 3-bit system would have one sign bit and two value bits giving a range of 3 to -3.
| Value | Decimal |
|---|---|
| 000 | 0 |
| 001 | 1 |
| 010 | 2 |
| 011 | 3 |
| 100 | -0 |
| 101 | -1 |
| 110 | -2 |
| 111 | -3 |
Note the second, negative, zero. It is also difficult to perform operations on these numbers, so this encoding is hardly ever used.
To make mathematical operations easier to perform, one's compliment defines negative numbers counting from the maximum value. To get the one's complement of X, take (2^N - 1) - X. This operation is equivalent to negating (flipping) all the bits in X. A bitwise NOT of X is sometimes written ~X.
| Value | Decimal |
|---|---|
| 000 | 0 |
| 001 | 1 |
| 010 | 2 |
| 011 | 3 |
| 100 | -3 |
| 101 | -2 |
| 110 | -1 |
| 111 | -0 |
Again, this encoding has two zeros such that 2 - 2 is negative zero, not zero.
Two's compliment works similarly to one's compliment, but shifts the negative values to do away with -0. The two's compliment of X is (2^N - 1) - X + 1, which again negates all bits in X but then adds one.
| Value | Decimal |
|---|---|
| 000 | 0 |
| 001 | 1 |
| 010 | 2 |
| 011 | 3 |
| 100 | -4 |
| 101 | -3 |
| 110 | -2 |
| 111 | -1 |
This encoding covers the range 2^(N-1) to -2^(N-1) + 1, has no ambiguous numbers and makes mathematical operations straightforward.