Intermediate Chapter 25 · 25 min read · Module 2: Operators and Expressions
Bitwise Operators
- After this chapter you can write integers in binary and read binary output.
- You can use &, |, ^, ~, << and >> and predict their results.
- You can use bit masks to test, set, clear and toggle a single bit.
- You can explain how << and >> relate to multiplying and dividing by powers of two.
- You can tell the difference between & and the logical keyword and.
Inside the computer every integer is stored as a row of bits, each one either 0 or 1. Most of the time you do not need to think about this, because Python shows you ordinary decimal numbers. Bitwise operators let you reach inside and work on those bits one at a time.
Python has six bitwise operators: AND (&), OR (|), XOR (^), NOT (~), left shift (<<) and right shift (>>). They are used in low-level code such as network addresses, file permissions, graphics, compression and games, and they also appear often in interviews and exams.
In this chapter you will first learn to read numbers in binary. Then you will use each operator on small examples, learn the bit mask patterns, and see how shifting is a quick way to multiply or divide by powers of two.
Binary numbers in Python
A binary number uses only the digits 0 and 1. Each position is worth twice the position on its right: 1, 2, 4, 8, 16 and so on from the right side. So binary 1011 means 8 + 0 + 2 + 1 = 11. In Python you can write a binary number with the prefix 0b, as in 0b1011. The built-in bin() turns an integer into a binary string, and the format code 08b in an f-string prints it with leading zeros to 8 digits.
x = 0b1011
print(x)
print(bin(11))
print(f"{5:08b}")
print(int("1111", 2))AND, OR and XOR
These three operators compare two numbers bit by bit. AND (&) gives 1 only when both bits are 1. OR (|) gives 1 when at least one bit is 1. XOR (^) gives 1 when the two bits are different. The table below shows the rule for one pair of bits.
| a | b | a & b | a | b | a ^ b |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Take 12 and 10. In binary they are 1100 and 1010. AND gives 1000 (8), OR gives 1110 (14) and XOR gives 0110 (6). Do not mix up & with the keyword and: the keyword works on whole truth values, while & works on every bit of integers.
a = 12
b = 10
print(f"{a:04b} {b:04b}")
print(a & b, f"{a & b:04b}")
print(a | b, f"{a | b:04b}")
print(a ^ b, f"{a ^ b:04b}")NOT and the shifts
The NOT operator ~ flips every bit. Because Python integers can be negative and have no fixed size, the result follows the simple rule ~x == -x - 1. So ~5 is -6, and ~0 is -1. Do not expect the answer to be only a few bits long.
The shift operators move all bits to the left or right. x << n shifts the bits n places left and fills with zeros, which is the same as multiplying by 2 to the power n. x >> n shifts right and drops the lowest bits, which is the same as floor division by 2 to the power n. So 3 << 2 is 12, and 13 >> 2 is 3.
print(~5)
print(~0)
print(3 << 2)
print(13 >> 2)
print(1 << 10)
print(-8 >> 1)Bit masks and flags
A mask is a number with chosen bits set to 1, used with a bitwise operator to work on those bits only. The usual patterns are: test a bit with x & mask, set it with x | mask, clear it with x & ~mask, and toggle it with x ^ mask. The mask for bit number k is 1 << k, counting from 0 on the right.
This is how file permissions, option flags and small yes/no settings are packed into a single number. One integer can hold many on/off switches, which saves space and makes it easy to combine them with |. A neat trick: n & (n - 1) clears the lowest set bit, and n & 1 tells you whether n is odd.
flags = 0b0101
mask = 1 << 1
print(bool(flags & mask))
flags = flags | mask
print(f"{flags:04b}")
flags = flags & ~(1 << 2)
print(f"{flags:04b}")
flags = flags ^ 0b0001
print(f"{flags:04b}")READ = 4
WRITE = 2
EXEC = 1
perm = READ | WRITE
print(perm)
print(bool(perm & WRITE))
print(bool(perm & EXEC))
print(7 & 1, 8 & 1)Bitwise operators also work on bool values and on sets in a different way: for sets, &, | and ^ mean intersection, union and symmetric difference. For floats they raise a TypeError, because floats have no simple bit pattern in Python.
Python syntax
result = a & b # also |, ^result = ~ashifted = a << n # or a >> na &= mask # also |=, ^=, <<=, >>=Real-world applications
- File permissions and option flags packed in one number.
- Network addresses and subnet masks.
- Fast multiplication or division by powers of two.
- Graphics, colours and pixel manipulation.
- Checksums, encryption and compression algorithms.
Common mistakes
Fix: & works on bits and has higher precedence. Use and/or for conditions.
Fix: Remember Python integers are unlimited, so ~5 is -6 and not a small positive number.
Fix: + binds tighter than <<, so this shifts by 2. Use brackets to show your intent.
Fix: ^ is XOR. Use ** for powers.
Fix: Bit positions start from 0 at the rightmost bit, so mask = 1 << k.
Important tips
- Print numbers with f"{x:08b}" to see the bits.
- Use named constants for flags such as READ = 4.
- Use brackets around bitwise parts of a longer expression to make it easy to read.
- n & 1 is a quick odd/even test.
- Use x << n for fast multiplication only when it makes the intent clear.
Key points summary
- Bitwise operators work on the binary form of integers.
- & needs both bits 1, | needs one, ^ needs them different.
- ~x equals -x - 1.
- x << n multiplies by 2n, x >> n floors division by 2n.
- Masks test, set, clear and toggle bits.
- Precedence: arithmetic, then shifts, then &, ^, |, then comparisons.
- Python integers have no fixed width.
Exam and interview points
- Know the truth tables of AND, OR and XOR.
- ~x == -x - 1.
- x << n == x * 2n; x >> n == x // 2n.
- n & (n - 1) clears the lowest set bit.
- XOR of a number with itself is 0 and with 0 is itself.
- Precedence order: + - then << >> then & then ^ then | then comparisons.
Quick revision
- & both, | either, ^ different.
- ~x = -x - 1.
- << multiplies by 2**n, >> divides.
- mask = 1 << k.
- Test x & mask, set x | mask, clear x & ~mask, toggle x ^ mask.
- Use brackets for clarity in mixed expressions.
Frequently asked questions
What is the difference between & and and?
& compares each bit of two integers and returns an integer. The keyword and works on truth values and returns one of its operands.
Why is ~5 equal to -6?
Python uses two's complement ideas for negatives, so flipping all bits of x gives -x - 1.
Is x << 1 faster than x * 2?
It does the same job, and in Python the speed difference is tiny. Choose the one that is clearer for the reader.
Is ^ the power operator?
No, ^ is bitwise XOR. The power operator is **.
Practise this chapter
22 practice questions Take the chapter quiz