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