Why is it that ~2 is equal to -3? How does ~
operator work?
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)