bit-wise operation unary ~ (invert)

You are exactly right. It’s an artifact of two’s complement integer representation.

In 16 bits, 1 is represented as 0000 0000 0000 0001. Inverted, you get 1111 1111 1111 1110, which is -2. Similarly, 15 is 0000 0000 0000 1111. Inverted, you get 1111 1111 1111 0000, which is -16.

In general, ~n = -n - 1

Leave a Comment