Adding Two's Complement Numbers

Introduction

Two's complement is wonderful.

Suppose you want to add two 2C 4-bit numbers: x3x2x1x0 and y3y2y1y0.

Here's pseudo-code to add the two numbers:

   int carry = 0 ;
   for ( int i = 0 ; i < N ; i++ )
     { 
        int sum = xi + yi + carry ;
        zi = sum % 2 ;
        if ( sum >= 2 )
           carry = 1 ;
     }
Did you notice something? It looks the same as adding 2 4-bit UB numbers?

If you tried to perform UB style addition (which is the standard kind of addition) on SM or 1C, you would not get the correct answer.

However, if you do UB style addition on numbers represented in 2C, the answer is correct, provided no overflow occurs. That's what's great about 2C. You can add numbers in 2C representation in exactly the same way you add them if they were in UB representation, and it gives you the right answer!

An Example

If you try the same example as in the previous set of notes, you get 1101 (which is -3 in 2C) plus 1101 (-3 again) which results in 1010, which is -6 in 2C. As before, we throw out the fifth bit.

In fact, this example works in 2C (i.e., produces a valid answer), but overflows in UB!

Overflow in 2C addition

Overflow can be detected in 2C addition by exclusive-ORing the carry-in to the most significant column (the leftmost column) and the carry-out. For a more detailed explanation of why, read the class notes on overflow.

Summary

When adding two k-bit 2C numbers, we apply the same rules of addition as we did for two k-bit UB numbers. The result is a k-bit 2C number. Provided the result did not overflow, the answer is correct in 2C.

This is one major reason why we use 2C representation for signed integers.

Web Accessibility