Python Bitwise Operators
In this page:
Bitwise AND and OR
Bitwise operators act on the individual binary bits of an integer rather than its value as a whole. & (AND) sets each output bit to 1 only where both inputs have a 1 in that position, and | (OR) sets it to 1 if either input does — the same logic gates used in digital electronics, just applied to numbers.
Example: Bitwise AND and OR
print(6 & 3)
print(6 | 3)
Bitwise XOR
^ (XOR) sets a bit to 1 only when the corresponding input bits differ — one 1 and one 0 — and to 0 when they match. This property makes XOR useful for toggling bits and for lightweight checksums.
Example: Bitwise XOR
print(6 ^ 3)
Bitwise NOT
~ (NOT) is a unary operator that flips every bit of its operand, which mathematically works out to -(x + 1) for any integer x due to how Python represents negative numbers — a detail that surprises people expecting a simple bit-flip on the visible digits.
Example: Bitwise NOT
print(~5)
Shift Operators
<< shifts bits left, inserting zeros on the right (equivalent to multiplying by 2 per position shifted), while >> shifts bits right, which is equivalent to integer division by 2 per position — both are fast alternatives to multiplication or division by powers of two.
Example: Shift Operators
print(1 << 3)
print(16 >> 2)
Bitwise Flags
Because a single integer holds many bits, programs sometimes pack several true/false flags into one number and use bitwise operators to set, clear, or test individual flags — a compact technique borrowed from lower-level systems programming.
Example: Bitwise Flags
READ = 1
WRITE = 2
permissions = READ | WRITE
print(permissions & WRITE != 0)
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators