Bitwise
- Python course
- Beginner
- Lesson 27/116
- 4 min
Learn &, |, ^, ~, <<, >> bitwise operators.
Bitwise operators
Bitwise operators work on the binary representation of numbers: & and, | or, ^ xor, ~ not, << left shift, >> right shift.
print(5 & 3) # 1 (0101 & 0011 = 0001)
print(5 | 3) # 7 (0101 | 0011 = 0111)
print(5 << 1) # 10 (left shift)These operators are used for low-level programming and performance. They are rarely needed in everyday code.
Shift operators
<< left shift moves each bit one position left; it is equivalent to multiplying by 2. >> right shift is equivalent to dividing by 2.
print(4 << 1) # 8 (4 * 2)
print(8 >> 1) # 4 (8 / 2)These operators are used for fast multiply/divide but can make code unreadable. Modern Python prefers explicit multiply/divide.
Practice Print bitwise operations
Print print(5 & 3) and print(5 | 3).
Starter code
# Bitwise operationsSample solution
print(5 & 3)
print(5 | 3)Expected output
1 7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is 5 & 3?
- 7
- 1 Correct answer
- 2
- 0
Explanation: & is bitwise and; 0101 & 0011 = 0001.
2 Bitwise or
print(5 ____ 3)
print(5 | 3)
Explanation: | is the bitwise or operator.
3 Match the bitwise operators
| Term | Meaning |
|---|---|
& |
Bitwise and |
| |
Bitwise or |
^ |
Bitwise xor |
<< |
Left shift |