Two’s complement is a method of representing signed integers in binary.
For a -bit long bit string in two’s complement, a at the first bit (or the -th from the right) represents the most negative value possible () for this string. The rest of the bits represent the original (positive) values assigned to them in binary.
The signed integer represented by the binary string is therefore: where is the -th bit counting from the right and is the length of the binary string.
Two’s complement for 8-bit signed integers:
Decimal | Two’s Complement Binary |
---|---|
0 | 0000 0000 |
1 | 0000 0001 |
2 | 0000 0010 |
126 | 0111 1110 |
127 | 0111 1111 |
−128 | 1000 0000 |
−127 | 1000 0001 |
−126 | 1000 0010 |
−2 | 1111 1110 |
−1 | 1111 1111 |
To negate a signed number in two’s complement, flip all bits and add one (~n + 1
).
Therefore, to convert a negative decimal number to two’s complement:
- Find the absolute value of the number in binary
- Negate the absolute value (flip all bits and add one—“taking the two’s complement”).