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

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

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

15条回答
  •  执念已碎
    2020-11-22 08:17

    I think for most people the confusion part comes from the difference between decimal number and signed binary number, so lets clarify it first:

    for human decimal world: 01 means 1, -01 means -1, for computer's binary world: 101 means 5 if it is unsigned. 101 means (-4 + 1) if is signed while the signed digit is at position x. | x

    so 2's flipped bit = ~2 = ~(010) = 101 = -4 + 1 = -3 the confusion comes from mixing up the signed result(101=-3) and the unsinged result(101=5)

提交回复
热议问题