With the ripple carry adder, we can add two numbers. But what about subtraction? 3 minus 5 is -2, and since bits only have 0 and 1, we need an agreement for writing the minus sign with 0s and 1s too. How do computers represent negative numbers?
The first idea that comes to mind is to use the leading bit as the sign: 0 means positive, 1 means negative, and the remaining 7 bits are the magnitude. This is called sign-magnitude.
But now there are two zeros: 00000000 (+0) and 10000000 (-0). Because the
same number has two bit patterns, comparisons need special handling.
Addition is even more awkward. To compute 1 + (-1), we put 00000001 +
10000001 into the adder and get 10000010, which is
-2. To get the right answer, we would have to build a separate circuit that
looks at the signs and subtracts the smaller from the larger.
Could negative numbers go straight through the adder we already have?
Another way to represent negative numbers is two’s complement. In two’s
complement, -x is written by flipping every bit of the positive number x and
then adding 1. 5 is 00000101, so flipping gives 11111010, and adding 1 gives
11111011, which is -5. With 8 bits it covers -128 to 127, and there is only
one zero.
00000000, so there is only one zero.The nice thing about two’s complement is that the adder gives the right answer as is. To compute A - B, add the two’s complement of B to A. There is no need to build a separate subtraction circuit.
Change the bits in the two rows and add them. If you put a negative number −B in the bottom row, the result is A − B, the top row A minus B.
However, 8-bit two’s complement only holds -128 to 127. Adding 01100100 (100)
to 01100100 (100) gives 11001000, and because its leading bit is 1, it reads
as −56. A result that goes out of range like this is called an overflow.
Flipping every bit of x gives 255 - x, and adding 1 gives 256 - x. So adding the two’s complement of B to A gives A + 256 - B. An 8-bit adder throws away the carry that overflows into the 9th place, which is 2⁸ = 256, leaving A - B.
The circuits we have built so far lose their result once the calculation is done. Even the Fibonacci sequence, which keeps adding the previous two values, would have to start over every time if it couldn’t remember earlier results. In the next post, let’s build a circuit that stores information with logic gates.
Real CPUs report separately whether each addition overflowed. When two 8-bit two's complement numbers go into the adder, which condition matches overflow exactly?