Two's Complement Explained
📣 Sponsor
Binary makes it really easy to add two numbers together, but adding a negative number is a little trickier. We run into a number of problems when trying to represent negative numbers in binary. To solve this we use Two's Complement, or signed notation. Two's complement is how we convert numbers to negative. Let's look at an 8-bit example. Using 8-bit means we can use numbers up to 255.
// Below is how we represent 9
0000 1001
// This means 2^0 + 0^1 + 0^2 + 2^3 + 0^4 + 0^5 + 0^6 = 9
Two's Complement is essentially a way to take these 8 bits, and also represent negative numbers. It will also work for other lengths of bits (i.e. 16-bit, or 32-bit) In Two's Complement, the first bit is used to represent if the number is positive or negative, so we can't use it to store data. As such, for our 8-bits, we can store values between 127 and -128 using 8 bits and Two's Complement.
To do Two's Complement, the first thing we do is invert the number except the first bit.
// Below is how we represent 9
0000 1001
// This means 2^0 + 0^1 + 0^2 + 2^3 + 0^4 + 0^5 + 0^6 = 9
// Let's invert our binary, excluding the first bit..
0111 0110
// And since we want to indicate it's negative, we set the first bit to 1.
1111 0110
// Finally, we add 1 to this number.
// So negative 9 (-9) can be represented by the following:
1111 0111
In short, to calculate Two's Complement:
- Invert the binary, and change the first digit to a 1, so 0000 1001 becomes 1111 0110
- Add 1 to the number, so 1111 0110 becomes 1111 0111
So our representation of -9 in Binary using Two's Complement is 1111 0111. To calculate this mathematically, we need to subtract the number in the first position from the total. That means:
20 + 21 + 22 + 03 + 24 + 25 + 26 - 27 which is equal to -9
Let's look at how we might use this in calculation:
// Let's try doing some arithmetic with Two's Complement.
// The below number represents 8
0000 1000
// And then we have our -9
1111 0111
// Let's try and add these, i.e. 8 + -9. Adding binary is the same as with decimals
// That means we just add the numbers above and below each other, and carry over anything else.
1111 0111
0000 1000 +
-----------
1111 1111
We know that 8 + -9 = -1. If we convert 1111 1111 back to decimal, using the method we previously used:
20 + 21 + 22 + 23 + 24 + 25 + 26 - 27 = -1
This is a simple example, so here is another version with carries:
// The below number represents 14
0000 1110
// And then we have our -9
1111 0111
// Let's try adding 14 + -9, or 14 - 9
// Since we have to carry numbers here, that working out is shown as well
1111 11
0000 1110
1111 0111 +
-----------
0000 0101
// The final carried 1 is ignored since it is outside our 8 bit space, leaving us with only 8 bits rather than 9.
So we know that 14 - 9 = 5, is that what our binary shows too? Let's see:
20 + 01 + 22 + 03 + 04 + 05 + 06 - 07 = 5
In summary, Two's Complement makes it super easy to add and subtract numbers.