问题
in refereing to bit-wise operators, what is the difference between ! and ~ ? I feel like they both flip the bits, but 1 maybe adds a 1 to the final answer?
~0xC4
compared to
!0xC4
Thanks!
回答1:
! is not a bitwise operator, it's a boolean operator.
The boolean operators operate on truth values, which are generally int. Any non-zero value is true, while 0 is false. The result is always 1 for true, 0 for false.
!is boolean not&&is boolean and||is boolean or
These are the ones used in e.g. if since it needs a boolean value. The boolean and/or operators are also short-circuiting, which means they stop evaluating when the result is known. This is good, it means 1 || crash_and_burn() will never crash and burn.
But the bitwise operators operate on each bit of the integer-typed argument(s), after promotions and such of course.
~is bitwise not&is bitwise and|is bitwise or^is bitwise exlusive-or (xor)
The bitwise operators are (of course) not short-circuiting, that wouldn't make any sense since they just operate on pairs of bits. Note that while there is a ^ bitwise operator, there is no ^^ boolean xor operator.
回答2:
~0xC4 flips bits and does this:
1100 0100 (0xC4) --> 0011 1011 (0x3B)
!0xC4 flips logical truth value and does this:
True (0xC4) --> False (0)
回答3:
! and ~ are two different types of operators. ! is the logical negation and ~ is the bitwise negation.
Logical operators are those which use mathematical logic.
For example: Sally went to the market and bought milk.
If p: Sally went to the market.
And q: Sally bought milk.
Then the statement can be shown as p && q.
Now, Bitwise operators are those that play with the binary representation of each number.
If p = 10 this can be expressed as p = 1010 (binary).
And q = 12 this can be expressed as q = 1100 (binary).
Then p & q = 1000 (binary).
Same for ! and ~ .
!p = Sally did not go to the market.
~p = 0101.
In C (and C++) there is no separation between booleans (True False ideas) and int. Which means that booleans are represented by integers as True = 1 and False = 0.
Here 0xC4 = 1100 0100
So, !0xC4 = 0000 0000 and ~0xC4 = 0011 1011 [0x3B].
Tip: If you wish to convert a certain variable to boolean (ie x = 5 -> x = 1) then use !!x.
!!x -> !(!(5)) -> !(0) -> 1
来源:https://stackoverflow.com/questions/16338928/difference-between-similar-bitwise-operators