The discussion so far in this appendix has focused on positive numbers. In this section, we explain how computers represent negative numbers using two’s complement notation. First we explain how the two’s complement of a binary number is formed, then we show why it represents the negative value of the given binary number.
Consider a machine with 32-bit integers. Suppose
int value = 13;
The 32-bit representation of value
is
00000000 00000000 00000000 00001101
To form the negative of value
we first form its one’s complement by applying C++’s bitwise complement operator (~
):
onesComplementOfValue = ~value;
Internally, ~value
is now value
with each of its bits reversed—ones become zeros and zeros become ones, as follows:
value:
00000000 00000000 00000000 00001101
~value
(i.e., value
’s one’s complement):
11111111 11111111 11111111 11110010
To form the two’s complement of value
, we simply add 1 to value
’s one’s complement. Thus
Two’s complement of value
:
11111111 11111111 11111111 11110011
Now if this is in fact equal to –13, we should be able to add it to binary 13 and obtain a result of 0. Let’s try this:
00000000 00000000 00000000 00001101
+11111111 11111111 11111111 11110011
------------------------------------
00000000 00000000 00000000 00000000
The carry bit coming out of the leftmost column is discarded and we indeed get 0 as a result. If we add the one’s complement of a number to the number, the result will be all 1s. The key to getting a result of all zeros is that the two’s complement is one more than the one’s complement. The addition of 1 causes each column to add to 0 with a carry of 1. The carry keeps moving leftward until it is discarded from the leftmost bit, and thus the resulting number is all zeros.
Computers actually perform a subtraction, such as
x = a - value;
by adding the two’s complement of value
to a
, as follows:
x = a + (~value + 1);
Suppose a
is 27 and value
is 13 as before. If the two’s complement of value
is actually the negative of value
, then adding the two’s complement of value to a
should produce the result 14. Let’s try this:
a (i.e., 27) +(~value + 1) |
00000000 00000000 00000000 00011011 +11111111 11111111 11111111 11110011 ------------------------------------ 00000000 00000000 00000000 00001110 |
which is indeed equal to 14.