8 Signed numbers

Since we mentioned ``deficit'', how do we represent negative integers?

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 $c_1(x)$ to represent one's-complement of $x$.

Two's-complement is based on one's-complement. Let us use $c_2$ to represent two's-complement. The definition is, then, $c_2(x)=c_1(x)+1$. 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:


$\displaystyle c_2(1101_2)$ $\textstyle =$ $\displaystyle c_1(1101_2) + 1$ (14)
  $\textstyle =$ $\displaystyle 0010_2 + 1$ (15)
  $\textstyle =$ $\displaystyle 0011_2$ (16)

Great! How about $c_2(0011_2)$?


$\displaystyle c_2(0011_2)$ $\textstyle =$ $\displaystyle c_1(0011_2) + 1$ (17)
  $\textstyle =$ $\displaystyle 1100_2 + 1$ (18)
  $\textstyle =$ $\displaystyle 1101_2$ (19)

Don't you think two's-complement is starting to look like the negation operator? In other words, $c_2(c_2(x)) = x$. Let's try this on zero:


$\displaystyle c_2(0000_2)$ $\textstyle =$ $\displaystyle c_1(0000_2) + 1$ (20)
  $\textstyle =$ $\displaystyle 1111_2 + 1$ (21)
  $\textstyle =$ $\displaystyle 0$ (22)

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 $n$ digits (in this case, 4). So, it works out for 0!

Copyright © 2006-08-21 by Tak Auyeung