2's Complement Arithmetic


Here is a short list of 2's complement rules that I found at http://people.msoe.edu/~tritt/digtwosc.html.

Interpretations

The typical way of generating 2's complement values is by inverting the bits and adding one to the result. For example, the four bit 2's complement form of -410 would be generated by starting with 410 written in base 2, i.e. 0100, inverting the bits to give 1011 and adding one to give 1100. You must always pad the value being converted to the specified number of bits with zeros on the left before inverting the bits and adding one.

This process can also be used to determine a value in base 10. For example, inverting the bits of 1100 gives 0011 and adding one results in 0100 which would be interpreted as -410. But there is an alternate way to determine this value. Interpret the left most (highest order) bit as the negative of the corresponding power of 2. For example, -(23 ) + 22 = -8 + 4 = -410. I find this second method easier and generally use it myself.

Sign Extension

Since the left most bit is the sign bit and is interpreted differently from the others, the number of bits used to represent a negative value in 2's complement form is very important. For example, -4 as a 4-bit 2's complement value is 1100 as indicated above, as a 6-bit value it is 111100 (this can be demonstrated by generating or interpreting the value as described above).

In general, to increase the number of bits in a 2's complement representation extend the sign bit to the left. If the sign bit is a 1, all the bits added on the left are 1's. On the other hand, if the sign bit is a 0, all the added bits are 0's.

Arithmetic

I'll be using 4 bit values in the rest of my examples. For reference, these values are (you should be able to generate this table yourself):

2's CompBase 102's CompBase 102's CompBase 102's CompBase 10
1000-81100-40000001004
1001-71101-30001101015
1010-61110-20010201106
1011-51111-10011301117

Overflows

Mixed signs always works --

510 - 310 = 510 + (-310) = 0101 + 1101 = 1 | 0010 (ignore carry out of the sign bit) = 210
310 - 510 = 310 + (-510) = 0011 + 1011 = 1110 (no carry out of sign bit) = -210

Small, same sign works --

210 + 310 = 0010 + 0011 = 0101 (no carry out of sign bit) = 510
-310 + (-210) = 1101 + 1110 = 1 | 1011 (ignore carry out of sign bit) = -510

Large, same sign doesn't work, but problem can be detected --

710 + 610 = 0111 + 0110 = 1101 = -310 (wrong)
-510 + (-410) = 1011 + 1100 = 1 | 0111 = 710 (wrong)

Overflows can be detected by noting that the sign of the result differs from the sign of the two terms. This is clearly impossible. Another way to detect this type of overflow is that the carry into and out of the sign bit are always the same when overflow did not occur and are always different when one did occur.