Simple question about: ~

Daniel A. Glasser dag at chinet.UUCP
Thu Jan 28 12:25:22 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?
>	short int x, y = 12;
>		x = -y -1;
>vs.
>	short int x, y = 12;
>		x = ~y;	
>Both ways end up assigning x the value of -13.  K&R say something about
>the  ~ operator taking the one's complement of a number, but I didn't
>follow their explanation...  

in two's complement arithmetic, the additive inverse (negative) of
a number is computed by taking the 1's complement (all 1's become 0's,
0's become 1's) of the bit pattern and adding 1.

An example of this is:

	Decimal		     Binary
	   1		0000000000000001	start with the number
	  -2		1111111111111110	take one's complement
	  -1		1111111111111111	add 1

So, -x is the two's complement, ~x is the one's complement.
-x - 1 is the one's complement, ~x + 1 is the two's complement.

Does any of this make sense?

(CS -101)


-- 
					Daniel A. Glasser
					...!ihnp4!chinet!dag
					...!ihnp4!mwc!dag
					...!ihnp4!mwc!gorgon!dag
	One of those things that goes "BUMP!!! (ouch!)" in the night.



More information about the Comp.lang.c mailing list