I am trying to check if any bit of an int x equals to 1, and the answer is !!x. I googled a bit and didn't find anything about why this is correct.
So say if I have a number x is 1010.
What would !x be? What is the different between !x and ~x?
! is a logical operator which takes the value of the operand of scalar type.
To quote C11, chapter §6.5.3.3, Unary arithmetic operators
The result of the logical negation operator
!is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint. [...]
OTOH, ~ is a bitwise operator which performs bitwise negation of the operand of integer type.
Related,
The result of the
~operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. [...]
For example, consider binary number 10.
!10 is 0.~10 is 01.EDIT:
FWIW, is you use !!, the result you can get is either 0 or 1. OTOH, is you use ~~, you get back the original value of the operand.
The range of possible values of !x are 0 and 1.
~ (the bitwise complement) has the same range as its domain.
So ~~x will recover x, but !!x will not necessarily do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With