Logical vs bitwise
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
Bitwise = Bit by bit checking
# Example
Bitwise AND: 1011 & 0101 = 0001
Bitwise OR: 1011 | 0101 = 1111
Logical = Logical checking or in other words, you can say True/False
checking
# Example
# both are non-zero so the result is True
Logical AND: 1011 && 0101 = 1 (True)
# one number is zero so the result is False
Logical AND: 1011 && 0000 = 0 (False)
# one number is non-zero so the result is non-zero which is True
Logical OR: 1011 || 0000 = 1 (True)
# both numbers are zero so the result is zero which is False
Logical OR: 0000 || 0000 = 0 (False)
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)
----------- = 1101
(13)
Meaning it would print 13
.