Path: utzoo!utgpu!water!watmath!clyde!cbosgd!ihnp4!homxb!twitch!anuck!jrl From: jrl@anuck.UUCP (j.r.lupien) Newsgroups: comp.lang.c Subject: Re: Simple question about: ~ Summary: -1 is usually "all bits on" Message-ID: <459@anuck.UUCP> Date: 27 Jan 88 18:46:28 GMT References: <1620006@hpcilzb.HP.COM> Organization: AT&T Bell Labs, Andover Ma. Lines: 50 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. > P.S. This was on a machine where a short int is 16 bits. Ones complement means "change the state of each bit in the word", 1's => 0, 0's => 1. Most C implementations use "twos complement" for negative integers. This means that, for your machine, a -1 is represented as: 0xFFFF or b1111111111111111 So, if we do -1 -y, you have b1111111111111111 - b0000000000001100 -------------------- b1111111111110011 which happens to be the one's complement. As you can see, whatever pattern of bits appears as the diminuend in this subtraction is going to be inverted. If y is negative, you should still get the inverted bit pattern, but you may get an overflow. Actually, this is a somewhat simple way to look at things, in that it only answers the question that was asked, and fails to appropriately expand on the implementation issues that arise. For instance, the "subtract" operation may exist as an opcode on the machine, or it may not. If not, it is implemented as a special form of "add the twos complement of the diminuend", a sort of "to subtract, add the negative" implementation. To get back to the question, I use ~ for bitwise inversion. It is probably best to stick with bitwise operators for bitwise operations and arithmetic operators for arithmetic operations. This way, the vagaries of implementation are sidestepped. Implementors are responsible for assuring that these operations work correctly, whereas "tricks" have to be tested anew each time you port. John R. Lupien ihnp4!mvuxa!anuxh!jrl