Why is it that ~2 is equal to -3? How does ~
operator work?
As others mentioned ~
just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.
One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3
as the number to which 3
should be added in order to get zero and you'll see that this number is 1101
, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.
1101 +
0011 // 3
=
10000
=
0000 // lose carry bit because integers have a constant number of bits.
Therefore 1101
is -3
, flip the bits you get 0010
which is two.