bitwise negation operator

can any one tell me how ~ operator works.,
int i=2;

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

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


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
~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.