bitwise negation operator

Sep 3, 2012 at 5:05pm
can any one tell me how ~ operator works.,
int i=2;
printf("%d",~i);

when i did so, the o/p comes as -3,how..????
Sep 3, 2012 at 5:11pm
closed account (zb0S216C)
It inverts all the bits of its operand. The resulting value is of course the opposite of its operand.

Wazzak
Sep 3, 2012 at 5:11pm
This operator reverse each bit of an integral type. So if a bit had 1 then it will have 0 and vice versa.

2 can be represented in hexadecimal notation as

00 00 00 02

after applying the ooperator ~ we get

FF FF FF FD

which is equivalent to -3


There is so-called two-compliment operation. For example if you have a value equal to 2 then that to make it -2 yu can write ~2 + 1. For example


std::cout << ~2 + 1 << std::endl;
Last edited on Sep 3, 2012 at 5:36pm
Sep 3, 2012 at 5:15pm
~changes all the bits of the variable, including the bit containing the sign

Your example (with 16 bit variables)
2 is 00000000 00000010
-3 is 11111111 11111101

If you just want to change the sign of an int, just use the - operator
Topic archived. No new replies allowed.