~
flips the bits in the value.
Why ~2
is -3
has to do with how numbers are represented bitwise. Numbers are represented as two's complement.
So, 2 is the binary value
00000010
And ~2 flips the bits so the value is now:
11111101
Which, is the binary representation of -3.