# Two’s Complement

As you may know, computers store everything in memory in the form of 1s and 0s. This might raise the question then how does a computer know if the number it has stored is a positive or a negative number. The answer is a system called Two’s Complement. For the following explanation we will be working with 8-bit numbers (0000 0000) so that we can have a small simple visual aid as we go through the steps of reading two’s complement.

When dealing with two’s complement the most significant bit of the binary number is reserved for the sign of the number (X000 0000). While positive numbers and 0 will start with a 0, negative numbers will start with a 1. To determine the two’s complement representation of a number you first take the normal binary of the number. Remember that your number must fit in a number of bits equal to your storage size minus 1. So since we are using 8 bits our largest number is 127 (0111 1111). If the number you are converting is positive, or 0, then you are done. For example:

`0   = 0000 00008   = 0000 100016  = 0000 1111127 = 0111 1111`

If your number is negative we simply reverse every bit in the number, so 0’s become 1’s and vice versa, then we add one to the result. so if we were to take -8, we would first take the normal binary representation of its positive counterpart:

`0000 1000. Then we flip all the bits0000 1000 becomes 1111 0111then we add 1 to it1111 0111 becomes 1111 1000. `

And this gives us our two’s complement of -8. And so now our chart looks like this:

`0    = 0000 00008    = 0000 1000-8   = 1111 100016   = 1111 0001127  = 0111 1111-127 = 1000 0001`

This conversion process can also be used to convert the negative number to its positive counter part with one exception. To do so you follow the same steps, first you write it’s two’s complement version, so for -8:

`1111 1000Then we flip the bits so1111 1000 becomes 0000 0111then we add 1 so0000 0111 becomes 0000 1000`

The one exception is the minimum number you can store in a two’s complement with a given number of bits, and touches on one of the quirks of two’s complement. The smallest number you can store has an absolute value 1 higher than the largest number. In an 8-bit number this translate to 127 as your max and -128 as you minimum. The reason for this is that -128’s complement is -128. In two’s complement -128 is represented as 1000 0000.

`1000 0000Then we flip the bits so1000 0000 becomes 0111 1111then we add 1 so0111 1111 becomes 1000 0000`

Another quirk of two’s complement is that its max is smaller than an unsigned integer’s max due to reserving the most significant bit for the sign of the number. So our 8-bit has a min of -128 and a max 0f 127 in two’s complement but a min of 0 (since it has no sign) and a max of 255.

And that is how to take a number and store it using two’s complement.