Adding Unsigned Numbers

Introduction

Adding numbers in binary is pretty much the same as adding in base ten. In fact, you could argue that it's even easier.

Suppose you want to add two UB 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 ;
     }

An Example

Let's add 1101 to 1101 (assume both are 4-bit UB numbers).

Let the rightmost column be column 0, and the leftmost column be column 3.

First, add the right most column (column 0). Summing 1 + 1 results in 0, with a carry of 1 to column 1.

Then, add the two bits in column 1, plus the carry bit. Summing 0 + 0, plus the carry 1, results in 1, with a carry of 0 to column 2.

Then, add the two bits in column 2, plus the carry bit. Summing 1 + 1, plus the carry 0, results in 0, with a carry of 1 to column 3.

Finally, add the two bits in column 3, plus the carry bit. Summing 1 + 1, plus the carry 1, results in 1, with a carry of 1 to column 4. We've had to "create" a column 4 to place the fifth bit of the sum.

Since we add in hardware, the output usually has the same number of bits as the number of bits being added. Since we were adding two 4-bit UB numbers, the result should be a 4-bit result.

Thus, the additional bit in column 4 (which is circled) is often discarded, or used to detect overflow. The answer is the 4-bit result, drawn inside the rectangle.

Overflow in UB addition

Overflow can be detected in UB addition by checking if there is a carry out when summing the leftmost columns (plus the carry bit into the column). The leftmost columns are the most significant bits.

Summary

When adding two k-bit UB numbers, we apply rules of addition similar to those in base 10. The result is a k-bit UB number only because hardware doesn't add an additional bit. Thus, adding two 4-bit numbers creates a 4-bit result.

If the sum of two k-bit UB numbers causes a carry out of 1 into column k (as it did in the example above), there is overflow.

Web Accessibility