Binary Arithmetic Fun Facts 1. A trick for forming the 2's complement of an N-bit binary number X. Let i be the position of the rightmost 1 in X. 2C(X0...Xi) = X0...Xi, and, for j = i+1 to N-1, 2C(Xj) = complement of Xj. 2. Consider the operation X - Y. As you know, on the MC6811, the C bit is set when X_unsigned > Y_unsigned, which is true if the subtraction operation requires a borrow from the Nth position. Suppose we perform this operation by adding the 2's complement of Y to X, that is, X + 2C(X). You may have noticed that the carry resulting from this operation does not match the C bit values. Consider these examples: 5 - 1: C=0. Here's the corresponding addition operation, in binary (assuming 1-byte numbers): 5 is 00000101_2c -1 is + 11111111_2c -------------- 00000100_2c and there IS a carry 1 - 5: C=1. Here's the corresponding addition operation: 1 is 00000001_2c -5 is + 11111011_2c --------------- 11111100_2c and there is NOT a carry It turns out that when you perform the above operation, you should invert the carry! So, if a computer performs subtraction X-Y by adding the 2C of Y to X, the C bit is set to the inversion of the carry. Here's why. Let's consider 4 bits to make this easier. X - Y. X: 0000 0001 0010 0011 0100 0101 0110 0111 -X: 0000 1111 1110 1101 1100 1011 1010 1001 1000 Consider 0011, for example. C should be 0 for all the numbers on the second line to the left, and it should be 1 for all numbers on the second line to the right: X: 0011 -X: 0000 1111 1110 1101 1100 1011 1010 1001 1000 3 3 3 3 3 3 3 3 3 -0 -1 -2 -3 -4 -5 -6 -7 -8 ---- ----- --- --- ----- --- --- --- ---- 3 2 1 0 Note that, for each number on the top line, the number just to the right on the bottom line is its bitwise complement. If you add a number and its complement you do not get a carry (since for each position, one of the numbers is 1 and the other is 0). So, a carry never results from adding 3 + (-4), 4 + (-5), etc., because the second is the bitwise complement of the first. Now, as you go further right on the bottom line, 1's are removed and never added (i.e., the more negative a negative number, the fewer 1's there are). Thus, no carry can result by adding any of the numbers on the right either. Thus, in none of those cases is a carry generated, and in all those cases, C=1. By similiar reasoning, addition with any number on the second line under or to the right generates a carry, and in all these cases, C=0.