Why is it that ~2 is equal to -3? How does ~
operator work?
I know the answer for this question is posted a long back, but I wanted to share my answer for the same.
For finding the one’s complement of a number, first find its binary equivalent. Here, decimal number 2
is represented as 0000 0010
in binary form. Now taking its one’s complement by inverting (flipping all 1’s into 0’s and all 0’s into 1’s) all the digits of its binary representation, which will result in:
0000 0010 → 1111 1101
This is the one’s complement of the decimal number 2. And since the first bit, i.e., the sign bit is 1 in the binary number, it means that the sign is negative for the number it stored. (here, the number referred to is not 2 but the one’s complement of 2).
Now, since the numbers are stored as 2’s complement (taking the one’s complement of a number plus one), so to display this binary number, 1111 1101
, into decimal, first we need to find its 2’s complement, which will be:
1111 1101 → 0000 0010 + 1 → 0000 0011
This is the 2’s complement. The decimal representation of the binary number, 0000 0011
, is 3
. And, since the sign bit was one as mentioned above, so the resulting answer is -3
.
Hint: If you read this procedure carefully, then you would have observed that the result for the one’s complement operator is actually, the number (operand - on which this operator is applied) plus one with a negative sign. You can try this with other numbers too.