问题
What the different between logical operators and
, or
and bitwise analogs &
, |
in usage? Is there any difference in efficiency in various solutions?
回答1:
Logical operators operate on logical values, while bitwise operators operate on integer bits. Stop thinking about performance, and use them for they're meant for.
if x and y: # logical operation
...
z = z & 0xFF # bitwise operation
回答2:
Logical operators are used for booleans, since true
equals 1 and false
equals 0. If you use (binary) numbers other than 1 and 0, then any number that's not zero becomes a one.
Ex: int x = 5;
(101 in binary) int y = 0;
(0 in binary) In this case, printing x && y
would print 0
, because 101 was changed to 1, and 0 was kept at zero: this is the same as printing true && false
, which returns false
(0).
On the other hand, bitwise operators perform an operation on every single bit of the two operands (hence the term "bitwise").
Ex: int x = 5; int y = 8;
printing x | y
(bitwise OR) would calculate this:
000101
(5)| 1000
(8)
----------- = 1011
(11)
Meaning it would print 11
.
回答3:
Logical operators are these:
&& || == !
They allow you operate on logical values for example:
(true || false) // evaluates to true
(!true) // evaluates to false
Bitwise operators are these:
& | ^ ~
They allow you to operate on binary bits, like this:
~011 = 100
0101 & 0011 = 0001
来源:https://stackoverflow.com/questions/8418295/logical-vs-bitwise