Section 6.5
Computer arithmetic

If we know how to add two unsigned binary numbers together, and how to convert from 2's complement to decimal, we almost know everything about computer arithmetic for integers. Subtraction is done by negating the second number and adding it to the first. Multiplication is done by repeatedly adding one of the numbers to an ongoing sum while counting, and the division is done by repeatedly subtracting one of the numbers from the dividend while counting.

Let's go through some examples using 8 bit 2's complement arithmetic. First, let's try adding together two small positive numbers:

  0 0 1 1 0 1 0 1     +53
+ 0 1 0 0 0 1 1 1     +71
-----------------    ----
  0 1 1 1 1 1 0 0     124

So far so good. That was easy. Now what about

  0 1 0 1 1 1 1 1     +95
+ 0 1 0 0 1 0 0 1     +73
-----------------    ----
  1 0 1 0 1 0 0 0     168   ???????

But our rules above said that whenever the first bit of a 2's complement number was 1 then the number was negative, so we added two positives, 95+73, and got a negative number?

If we recall our observations, we see that the range of numbers in 8-bit 2's complement is -128 to +127. Thus, we get screwy answers when we add numbers that are too big and which cause the real sum to be larger than what we can represent. This is called overflow.

Notice that if we treated the above addition as unsigned numbers, everything is fine because 168 is 10101000, as long as we are looking at it as an unsigned number and not as a 2's complement number.

Now let's tackle adding two negatives:

    1 0 1 1 0 1 1 1     -73
  + 1 1 1 0 1 1 1 1     -17
  -----------------    ----
  1 1 0 1 0 0 1 1 0     -90

Again, if there is a final carry out, it gets thrown away. Everything works out fine and we get a negative answer. Remember that this will be true if our answer does not exceed -128.

What if we look at these as unsigned numbers?

  1 0 1 1 0 1 1 1     183
+ 1 1 1 0 1 1 1 1     239
-----------------   -----
  1 0 1 0 0 1 1 0     422

But 10100110 is only 166, not 422, so another form of overflow occurred. This has to do with throwing away that final carry out. If we had kept it, we would have had 110100110, which is 422.