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

后端 未结 15 1413
无人共我
无人共我 2020-11-22 07:46

Why is it that ~2 is equal to -3? How does ~ operator work?

15条回答
  •  不思量自难忘°
    2020-11-22 08:03

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

提交回复
热议问题