Python's bitwise operators operate on ... drumroll please ... bits! The following table lists the bitwise operators.
Operator | Meaning |
---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise NOT |
<< | Shift Bits Left |
>> | Shift Bits Right |
Here is a sample REPL session showing these operators in action:
>>> 1 & 0 0 >>> 1 & 1 1 >>> 1 | 0 1 >>> 0 | 0 0 >>>
So far, so good. Since Python's Boolean values True
and
False
are equal to 1
and 0
respectively
(try True == 1
in the REPL and see what you get), we can use
these bitwise operators with our bool
values to evaluate
Boolean
expressions. One of the group projects listed below asks you to write
a python program to print out a truth table.
Bitwise operators get a little weirder when we use them with integer values
other than 0
and 1
.
>>> 3 & 14 2 >>> 21 | 14 31 >>> 24 & 12 8 >>> 24 | 12 28 >>> 24 ^ 12 20 >>>
Then we have the shift operators.
>>> 1 << 1 2 >>> 1 << 3 8 >>> 14 >> 1 7 >>>
Finally, we have the bitwise not operator, ~
.
>>> ~ 0 -1 >>> ~ 1 -2 >>> ~ -256 255 >>>
What's up with those? This just seems to get weirder and weirder. We will divide these up in class and help each other find out.
The following is a list of mini-projects we can use to divide up a brief study of bitwise operators among our class: