~ (Bitwise NOT)
Performs the NOT operator on each bit. NOT
ayields the inverted value (a.k.a. one’s complement) of
a. The truth table for the NOT operation is:
a NOT a 0 1 1 0
Example:9 = 00000000000000000000000000001001 (base 2) -------------------------------- ~9 = 11111111111111111111111111110110 (base 2) = -10 (base 10)
Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.
Now lets look at the Logical NOT(!)
! (Logical NOT)
Mixing the two NOT operators together can produce some interesting results:
!~(-2) = false
!~(-1) = true
!~(0) = false
!~(1) = false
!~(2) = false
For all integer operands except -1, the net operand after applying the ~ operator for the ! operator would be truthy in nature resulting in FALSE.
When to use this special case ?
We can use the operators instead of the comparison operators, like this: