How does the bitwise complement operator (~ tilde) work?

Remember that negative numbers are stored as the two's complement of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits)

1111 1110

The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative.

So let's take a look at how we get ~2 = -3:

Here's two again:

0000 0010

Simply flip all the bits and we get:

1111 1101

Well, what's -3 look like in two's complement? Start with positive 3: 0000 0011, flip all the bits to 1111 1100, and add one to become negative value (-3), 1111 1101.

So if you simply invert the bits in 2, you get the two's complement representation of -3.

The complement operator (~) JUST FLIPS BITS. It is up to the machine to interpret these bits.


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