Explanation of Bitwise NOT Operator

Maxpm picture Maxpm · Nov 28, 2010 · Viewed 33.7k times · Source

Why is it that the bitwise NOT operator (~ in most languages) converts the following values like so:

-2 -> 1
-1 -> 0
0 -> -1
1 -> -2

Shouldn't -2 convert to 2, 1 convert to -1, etc.?

Answer

Phrogz picture Phrogz · Nov 28, 2010

See two's complement for the representation of negative integers in many languages. As you can see, -2 is represented by 1111110; if you invert all those bits you get 0000001, i.e. a value of 1.