7.6 Bitwise Operators
Python's bitwise operators — & | ^ ~ << >> — how they operate on an integer's binary representation, and the classic permission-flags bit manipulation pattern.
What Are They?
Operators that work on the individual bits of an integer’s binary representation, rather than its decimal value.
Why Are They Used?
Permission flags, low-level protocol parsing, and performance-sensitive bit manipulation.
Binary Representation
Every int has an underlying binary form — bin() displays it, and format() lets you control the padding:
>>> bin(5), bin(3)
('0b101', '0b11')
>>> format(5, '04b') # zero-padded to 4 bits
'0101'
&, |, and ^ applied bit-by-bit to 5 (0101) and 3 (0011):
| Bit position | a=5 (0101) | b=3 (0011) | a & b | a | b | a ^ b |
|---|---|---|---|---|---|
| bit 3 | 0 | 0 | 0 | 0 | 0 |
| bit 2 | 1 | 0 | 0 | 1 | 1 |
| bit 1 | 0 | 1 | 0 | 1 | 1 |
| bit 0 | 1 | 1 | 1 | 1 | 0 |
| Result | 0001 = 1 | 0111 = 7 | 0110 = 6 |
& (AND)
Each result bit is 1 only if both input bits are 1.
>>> 5 & 3
1
| (OR)
Each result bit is 1 if either input bit is 1.
>>> 5 | 3
7
^ (XOR)
Each result bit is 1 if the input bits differ.
>>> 5 ^ 3
6
~ (NOT)
Inverts every bit. In Python’s signed representation, this is equivalent to -(x + 1).
>>> ~5
-6
<< (Left Shift)
Shifts bits left, equivalent to multiplying by 2 per shifted position.
>>> 5 << 1
10
>> (Right Shift)
Shifts bits right, equivalent to floor-dividing by 2 per shifted position.
>>> 5 >> 1
2
Bit Manipulation Example
A classic real-world use: representing a set of independent permission flags in a single integer, using one bit per flag.
>>> READ, WRITE, EXECUTE = 4, 2, 1 # 100, 010, 001
>>> perms = READ | WRITE # combine flags
>>> bin(perms)
'0b110'
>>> bool(perms & READ) # check if READ flag is set
True
>>> bool(perms & EXECUTE) # check if EXECUTE flag is set
False
Quick Interview Answer
“Bitwise operators work on an integer’s binary representation rather than its decimal value:
&(AND) and|(OR) work bit-by-bit like their logical counterparts,^(XOR) is true only where bits differ,~inverts every bit (equivalent to-(x+1)in Python’s signed representation), and<</>>shift bits left/right, equivalent to multiplying or floor-dividing by a power of two. The classic real-world use is packing independent boolean flags — like permissions — into a single integer, one bit per flag, then testing a flag withperms & FLAG.”
Common Mistakes
- Confusing bitwise
&/|with logicaland/or— bitwise operators work bit-by-bit on integers (or set union/intersection, see 7.13 Operators with Different Data Types); logical operators work on truthy/falsy values as a whole. - Expecting
~5to be-5— Python’s two’s-complement-style signed representation makes it-(x + 1), so~5is-6. - Reaching for bit flags in application code where a set of named booleans or an
Enumwith flags would be far more readable.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form