Well, a quick-and-easy way is to use a bit (binary digit) to indicate whether other bits represent a magnitude in the positive direction or the negative direction. This approach is fine, except that it requires more logic to perform addition and subtraction because there are four possible combinations. Furthermore, it is also wasteful, because zero has two representations.
A better method, known as two's-complement, is used to handle the sign of
a number. Before we talk about two's-complement, let's talk about
one's-complement, which is also known as bitwise-not (the ~
operator in C). Note that this operator only works for binary numbers
that have a fixed length.
The bitwise-not operator takes each binary digit in a number, and change
it to the other one. For example, the binary number 1101(2)
has a one's-complement of 0010(2)
. Let us use
to represent one's-complement of
.
Two's-complement is based on one's-complement. Let us use to
represent two's-complement. The definition is, then,
.
Note that this addition is also a fixed-width operation.
Let us look at the binary pattern 1101(2)
, and figure out its
two's-complement:
![]() |
![]() |
![]() |
(14) |
![]() |
![]() |
(15) | |
![]() |
![]() |
(16) |
Great! How about ?
![]() |
![]() |
![]() |
(17) |
![]() |
![]() |
(18) | |
![]() |
![]() |
(19) |
Don't you think two's-complement is starting to look like the negation
operator? In other words,
. Let's try this on zero:
Line 22 seems to be wrong, shouldn't that be
10000_2
instead? Recall that we are using addition in a
fixed-width environment. In such an environment, the result consists of
the least significant digits (in this case, 4). So, it works out for
0!
Copyright © 2006-08-21 by Tak Auyeung