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

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

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

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:02

    As others mentioned ~ just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.

    One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3 as the number to which 3 should be added in order to get zero and you'll see that this number is 1101, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.

     1101 +
     0011 // 3
        =
    10000
        =
     0000 // lose carry bit because integers have a constant number of bits.
    

    Therefore 1101 is -3, flip the bits you get 0010 which is two.

提交回复
热议问题