Simple question about: ~
00704a-Liber
nevin1 at ihlpf.ATT.COM
Thu Jan 28 11:38:21 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...
.
.P.S. This was on a machine where a short int is 16 bits.
This is because you are working on a 2's complement machine.
To take the negative of a 2's complement number, you
invert all the bits (ie, take the 1's complement of the number which is
using '~'), then you add 1 to the result.
Therefore, on a 2's complement machine, ~y +1 === -y or, as you stated,
~y === -y - 1.
This is a machine dependent feature and is NOT guaranteed to be consistent
under all implementations of C.
--
_ __ NEVIN J. LIBER ..!ihnp4!ihlpf!nevin1 (312) 510-6194
' ) ) "The secret compartment of my ring I fill
/ / _ , __o ____ with an Underdog super-energy pill."
/ (_</_\/ <__/ / <_ These are solely MY opinions, not AT&T's, blah blah blah
More information about the Comp.lang.c
mailing list