Why sign extend works

By far the most common question that I'm getting in office hours is why sign extend works the way it does. I'll take a shot at explaining it here...

So, let's assume that I would like to add two binary numbers of different lengths. For example:

0101 + 01

It's a pretty simple matter to extend 11 with a pair of 0s to the left to make the numbers the same length. You do this all the time for decimal numbers:

0101 + 0001 = 0110

No problem. Let's to the same thing with subtraction and the same two values:

0101 - 01

add the zeros:

0101 - 0001

take the 2's compliment:

0101 + 1111



and all is well.

But what if we take the two's compliment before we extend 01 to 4 bits? In other words:

0101 + 11

If we add two zeros like we did earlier, we get the wrong answer:

0101 + 0011 = 1000

But, if we add two ones instead, we get the answer that we should:

0101 + 1111 = 0100

This is the situation we have with offset. The value is already in 2's compliment form before we extend it. Thus, we need to add 1's for negative numbers and 0's for positive numbers. As always, we can tell the difference between positive and negative because the high bit for a negative number is 1.