Simple question about: ~

Larry Jones scjones at sdrc.UUCP
Wed Jan 27 14:57:33 AEST 1988


In article <1620006 at hpcilzb.HP.COM>, tedj at hpcilzb.HP.COM (Ted Johnson) writes:
> 
> Could someone please explain why the following statements both give the
> same answer?
> 
> 		x = -y -1;
> 		x = ~y;	

Congratuations!  You've just discovered "two's complement".  This is the system
that most current computers use for representing integer values.  To fully
understand it, you need to first understand "one's complement".

In the one's complement, the negative of a number is represented by negating
each bit of the number.  For example, if you have the number 12 (00001100)
then -12 is (11110011).  This is called one's complement since adding a
number to its negative results in a one in each bit position.  This is what
the ~ operator does, it complements each bit in a number.

Although one's complement is a simple and easily understandable system, it has
a number of disadvantages, not the least of which is that +0 and -0 each have
representations.  Since most people expect to have a single representation for
zero, two's complement has become more popular.  Two's complement is just like
one's complement except that after you complement each bit, you add one to the
result.  Thus in two's complement notation -12 is (11110100).

So, on a two's complement machine, -y == ~y + 1 which can be rearranged into
the identity you discovered ~y == -y - 1.  Please note, however, that this is
NOT portable since there are still a few machines that use one's complement
arithmetic rather than two's complement.
-- 

----
Larry Jones                         UUCP: uunet!sdrc!scjones
SDRC                                MAIL: 2000 Eastman Dr., Milford, OH  45150
                                    AT&T: (513) 576-2070
"When all else fails, read the directions."



More information about the Comp.lang.c mailing list