Path: utzoo!mnetor!uunet!husc6!hao!oddjob!gargoyle!ihnp4!chinet!dag From: dag@chinet.UUCP (Daniel A. Glasser) Newsgroups: comp.lang.c Subject: Re: Simple question about: ~ Message-ID: <2148@chinet.UUCP> Date: 28 Jan 88 02:25:22 GMT References: <1620006@hpcilzb.HP.COM> Reply-To: dag@chinet.UUCP (Daniel A. Glasser) Organization: Chinet - Public Access Unix Lines: 38 In article <1620006@hpcilzb.HP.COM> tedj@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.