Bitwise Complement Operator (~ tilde)
The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1’s become 0’s and vice versa. The operator for the bitwise complement is ~ (Tilde).
Input: ~ 0000 0011
Output: 1111 1100
Input: 1110 0111
Output: 0001 1000
The bitwise complement operator should be used carefully. The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And the result may be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the sign bit).
n = 2
Binary form of 2 = 0010
Bitwise complement operation on 2 = ~ 0010
1101 is equivalent to decimal value 13.
Expected output: 13
Correct Output : -3
The compiler returns the 2’s complement of the input value.
Bitwise complement of 2 : -3
The bitwise complement of 2 (~2) is -3 instead of 13, but why?
When numbers are printed in base-10, the result of a NOT operation can be surprising. In particular, positive numbers can become negative and vice versa.
Let’s first find the binary representation of bitwise complement of 2 which is -3
The negative numbers are stored as the two’s complement of the positive counterpart.
Two’s complement is an operation on binary numbers. The 2’s complement of a number is equal to the complement of that number plus 1.
Bitwise complement Operation of 2 (~ 0010 ): 1101
Calculate 2’s complement of 3:
Binary form of 3 = 0011
1’s Complement of 3 = 1100
Adding 1 to 1’s complement = 1100 +1
2’s complement of 3 = 1101
The bitwise Complement of 2 is same as the binary representation of -3
Thus it can be concluded from the above example that-
- For any integer n, the bitwise complement of n will be -(n+1).
- Bitwise complement of N = ~N (represented in 2’s complement form).
- 2’complement of ~N= -(~(~N)+1) = -(N+1).