In mathematics, the additive inverse of a number n is the value, when added to n, produces zero. Here are a few examples, expressed in decimal:
6 + 6 = 0
0 + 0 = 0
1 + 1 = 0
Programs often include both subtraction and addition operations, but internally, the CPU really only performs addition. To get around this restriction, the computer uses the additive inverse. When subtracting A B, the CPU instead performs A + (B). For example, to simulate the subtraction of 4 from 6, the CPU adds 4 to 6:
6 + 4 = 2
Binary Twos Complement
When working with binary numbers, we use the term twos complement to refer to a numbers additive inverse. The twos complement of a number n is formed by reversing ns bits and adding 1. Here, for example, n equals the 4-bit number 0001:
N: | 0001 |
Reverse N: | 1110 |
Add 1: | 1111 |
The twos complement of n, when added to n, produces zero:
0001 + 1111 = 0000
It doesnt matter how many bits are used by n. The twos complement is formed using the same method:
N = 1 | 00000001 |
Reverse N: | 11111110 |
Add 1: | 11111111 |
N = 1 | 0000000000000001 |
Reverse N: | 1111111111111110 |
Add 1: | 1111111111111111 |
Here are some examples of 8-bit twos complements:
n(decimal) | n(binary) | NEG(n) | (decimal) |
+2 | 00000010 | 11111110 | 2 |
+16 | 00010000 | 11110000 | 16 |
+127 | 01111111 | 10000001 | 127 |