bit-wise operation unary ~ (invert)

Alcott picture Alcott · Sep 2, 2011 · Viewed 81.4k times · Source

I'm a little confused by the ~ operator. Code goes below:

a = 1
~a  #-2
b = 15
~b  #-16

How does ~ do work?

I thought, ~a would be something like:

0001 = a
1110 = ~a 

why not?

Answer

NullUserException picture NullUserException · Sep 2, 2011

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