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

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

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

相关标签:
15条回答
  • 2020-11-22 08:17

    This operation is a complement, not a negation.

    Consider that ~0 = -1, and work from there.

    The algorithm for negation is, "complement, increment".

    Did you know? There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-22 08:18

    The bit-wise operator is a unary operator which works on sign and magnitude method as per my experience and knowledge.

    For example ~2 would result in -3.

    This is because the bit-wise operator would first represent the number in sign and magnitude which is 0000 0010 (8 bit operator) where the MSB is the sign bit.

    Then later it would take the negative number of 2 which is -2.

    -2 is represented as 1000 0010 (8 bit operator) in sign and magnitude.

    Later it adds a 1 to the LSB (1000 0010 + 1) which gives you 1000 0011.

    Which is -3.

    0 讨论(0)
提交回复
热议问题