Explanation of Bitwise NOT Operator

前端 未结 7 1663
悲&欢浪女
悲&欢浪女 2020-11-30 07:00

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

-2 -> 1
-1 -> 0

7条回答
  •  离开以前
    2020-11-30 07:07

    This is because the bit-wise operator literally inverts each bit in the word. It is NOT strictly an arithmetic operation, it is a logic operation.

    -2 == %1110, ~-2 == ~%1110 = %0001 == 1 -1 == %1111, ~-1 == ~%1111 = %0000 == 0

    and so on.

    To go from -2 to 2, and 1 to -1 you need to use the arithmetic negation operation.

提交回复
热议问题