Arlington Tech Logo

AP Computer Science Principles

Bitwise Operators in Python


It's All Just Bits!

Python's bitwise operators operate on ... drumroll please ... bits! The following table lists the bitwise operators.

OperatorMeaning
&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:

REPL Session 1

>>> 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.

REPL Session 2

>>> 3 & 14 
2
>>> 21 | 14 
31
>>> 24 & 12 
8
>>> 24 | 12 
28
>>> 24 ^ 12 
20
>>>

Then we have the shift operators.

REPL Session 3

>>> 1 << 1 
2
>>> 1 << 3 
8
>>> 14 >> 1 
7
>>>

Finally, we have the bitwise not operator, ~.

REPL Session 4

>>> ~ 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.

Choose a Presentation

The following is a list of mini-projects we can use to divide up a brief study of bitwise operators among our class:

  1. Write a python program to print a truth table given a Boolean expression. The table should include one column for each operand and a final column for the expression.
  2. Study the examples in REPL Session 2 and create a presentation to give in class that explains these examples (and others) to your classmates.
  3. Study the examples in REPL Session 3 and create a presentation to give in class that explains these examples (and others) to your classmates.
  4. Study the examples in REPL Session 4 and create a presentation to give in class that explains these examples (and others) to your classmates.