When we extend our binary representations to include negative numbers,
there are several choices. For example, the sign and magnitude
approach is to have one bit for the sign and
bits for the
magnitude. The one's complement approach is to represent
negative numbers by having a bit for sign and
bits for the
magnitude when unsigned and to represent negation by flipping all
bits. Among other things, these representations have two
representations for zero, one positive and one negative. Nowadays,
most computers use two's complement which has the useful
property of being able to use the same addition circuits that we have
discussed for unsigned integers.
In two's complement, an non-negative number is represented by having a
zero in the high order bit (still called the sign bit) and
bits
in the normal unsigned format. This represents the numbers from
. The negation of a number
is chosen such that
.
To negate a number, one may invert all the bits and increment the
result. The sum of a number and the result of all its bits is
so one more than inverting all the bits gives zero because there are
only
bits. Note that this negation operation does not change
zero. After using the negation operation to define more values, there
is one combinations of bits which is undefined, a single bit set to
one followed by zeros. We define this to be
.
As with our unsigned integer representation, there is a simple formula for the value of a signed integer given its two's complement representation.
This is equivalent to our unsigned representation modulo
. You should convince yourself that the sign bit is set correctly
when adding two numbers unless there is overflow. Particularly, when
adding two negative numbers, the two sign bits set to one effectively
cancel each other out but there will be a carry bit from the lower
bits to set it unless the result would be less than
.
Changing the size of a signed integer is slightly more complicated
than with unsigned integers. When increasing the size, the old sign
bit is preserved and copied to the new sign bit. Note that
. This is called sign extension. Similarly, when
decreasing the size, the value remains the same as long as the two
high order bits are the same.
Since every combination of bits in two's complement represents a different integer, we can use the same equality circuits as for unsigned integers. When comparing two signed integers in two's complement, we can use almost the same hardware, except that the usage of the highest order bit needs to be reverse because it corresponds to a negative value now.