🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreePython Bitwise Operators: Meaning and Examples

When a bitwise symbol appears in Python code, the first task is to find out what it does to an integer. Python’s bitwise operators work on the binary digits of integers and return integer results.
This article explains what each operator returns and shows how a mask, an integer used to select bit positions, can check or change one bit.
TL;DR: Python Bitwise Operators
Python has six bitwise operators for combining, inverting and shifting the bits of integers.
- AND (&) keeps bits set in both operands, while OR (|) keeps bits set in either.
- XOR (^) keeps differing bits. NOT (~) inverts an integer using Python’s sign-extended integer model.
- Left shift (<<) multiplies by a power of two, while right shift (>>) floor-divides by one.
- Use a mask such as 1 << index to inspect or change one bit. Add parentheses to make mixed expressions clear.
What Are Python Bitwise Operators?
Bitwise operators work on corresponding positions in integer values, treating each position as a binary digit. The result is another integer, so these operators are useful when a value stores several flags or when code needs to inspect a particular bit.
| Operator | Meaning | Example |
|---|---|---|
| & | Bitwise AND: 1 only where both bits are 1 | 12 & 5 is 4 |
| | | Bitwise OR: 1 where either bit is 1 | 12 | 5 is 13 |
| ^ | Bitwise XOR: 1 where bits differ | 12 ^ 5 is 9 |
| ~ | Bitwise complement of one integer | ~12 is -13 |
| << | Shift left by a count | 12 << 1 is 24 |
| >> | Shift right by a count | 12 >> 2 is 3 |
For example, 12 is 0b1100 and 5 is 0b0101. Aligning those digits makes AND produce 0b0100, OR produce 0b1101 and XOR produce 0b1001.
Each binary digit represents a power of two, counted from the right starting at index zero. In 0b1100, the rightmost two positions are zero and the next two are one, giving 8 plus 4. That is why the integer value is 12.
Use bin() to view an integer in binary. The returned string starts with 0b for nonnegative values and exposes the digits that take part in an operation.
How to Use Python Bitwise Operators Step by Step
Run this example with Python 3 to compare the operator results and then use the same single-bit mask to inspect and modify a value.
Step 1: Compare two integers bit by bit
Save the following as bitwise_demo.py. The operands 12 and 5 have short binary forms, which makes the positions in each result visible.
a = 12
b = 5
print(f"a = {a} ({a:#06b})")
print(f"b = {b} ({b:#06b})")
print(f"a & b = {a & b} ({a & b:#06b})")
print(f"a | b = {a | b} ({a | b:#06b})")
print(f"a ^ b = {a ^ b} ({a ^ b:#06b})")
print(f"~a = {~a}")
print(f"a << 1 = {a << 1}")
print(f"a >> 2 = {a >> 2}")
print(f"-3 >> 1 = {-3 >> 1}")
print(f"~False = {~False}")
print(f"(12 | 5) & ~5 = {(12 | 5) & ~5}")
try:
print(5 << -1)
except ValueError as error:
print(f"negative shift: {type(error).__name__}: {error}")
mask = 1 << 2
print(f"bit 2 set in a: {bool(a & mask)}")
print(f"set bit 1 in a: {a | (1 << 1)}")
print(f"clear bit 2 in a: {a & ~(1 << 2)}")
print(f"toggle bit 0 in a: {a ^ 1}")
Run it with python3 bitwise_demo.py. I ran that command and got these values:
a = 12 (0b1100) b = 5 (0b0101) a & b = 4 (0b0100) a | b = 13 (0b1101) a ^ b = 9 (0b1001) ~a = -13 a << 1 = 24 a >> 2 = 3 -3 >> 1 = -2 ~False = -1 (12 | 5) & ~5 = 8 negative shift: ValueError: negative shift count bit 2 set in a: True set bit 1 in a: 14 clear bit 2 in a: 8 toggle bit 0 in a: 13

The binary results show the positions shared, combined or changed by the operands. The format specifier #06b prints the 0b prefix and pads each value to four binary digits. This makes the positions possible to compare directly.
Step 2: Use a mask to check or change one bit
A mask is an integer whose 1 bits select positions for an operation. AND tests a selected position, OR sets it, XOR toggles it and AND with the inverted mask clears it.
Bit indices count from the least significant digit, the rightmost one. Index 2 selects the 4’s place because shifting 1 left twice gives 0b0100. AND with that value leaves either 0 or 4, so wrap the test in bool() when the caller needs True or False.
In the output, testing bit 2 of 12 returns True because 0b1100 has a 1 in that position. Setting bit 1 produces 14. Clearing bit 2 produces 8, while toggling bit 0 changes 12 to 13.
For compact permissions, assign READ to 1 << 0 and WRITE to 1 << 1. Combine them with OR, then check for WRITE with AND.
Edge Cases: Negative Integers, Shifts and Precedence
Negative integers use sign extension in Python’s bitwise model, rather than a selected machine-word width. This explains why complement and right shift can differ from a fixed-width binary sketch.
| Case | What happens | Practical response |
|---|---|---|
| Complement, ~x | It equals -x – 1, so ~12 is -13 | Use a width mask such as ~x & 0xff when you specifically need an eight-bit result |
| Right shift a negative | -3 >> 1 is -2, equivalent to floor division by 2 | Account for rounding toward negative infinity |
| Negative shift count | 5 << -1 raises ValueError: negative shift count | Check that a computed count is zero or greater |
| Boolean complement | ~False is -1, and inversion on bool has been deprecated since Python 3.12 | Use not False for Boolean negation |
Shifting left by n positions multiplies by 2 to the power n. Shifting right performs floor division by that power, so an odd positive input loses its fractional part and a negative input rounds downward.
For an eight-bit value, AND with 0xff drops any higher bits.
Flipping the sign-extended representation gives ~x = -x – 1, so ~12 is -13 and ~0 is -1.
A shift count must be nonnegative. When the count comes from a variable, validate it before the shift so an invalid input does not raise ValueError. A count of zero leaves the original integer unchanged.
For conditions, use Boolean operators rather than combining comparisons with bitwise symbols. Python’s and and or short-circuit, so the second operand may not be evaluated. See the Python logical operators guide.
Python evaluates bitwise operations before comparisons, with AND binding more tightly than XOR and XOR more tightly than OR. All three bind before comparisons, so parentheses help make a condition’s intended order explicit.
- Write (value & mask) != 0 when testing whether selected bits are present.
- Do not replace a Boolean condition such as age >= 18 and has_ticket with age >= 18 & has_ticket.
For example, (12 | 5) & ~5 first combines the values with OR, then clears the bits present in 5, leaving 8.
Conclusion
Choose a bitwise operator by the positions you want to retain, combine, invert or move. Start with a small binary example, then use an explicit mask and parentheses when the expression grows.
- For a broader treatment of selecting and changing bits, read Python bit manipulation and masking techniques.
- Consult the Python integer bitwise operations reference for exact behavior and version-specific notes.
- Use the Python operator precedence reference when reviewing a mixed expression.
FAQ
These answers clarify common questions about bitwise operations in Python.
Does Python have bitwise operators?
Yes. Python provides &, |, ^, ~, <> for bitwise operations on integers.
Why does ~5 return -6 in Python?
Python’s integer complement follows ~x = -x – 1, so ~5 is -6. The model uses unlimited sign extension rather than a selected fixed width.
What is the difference between & and and in Python?
The & operator combines integer bits. The and keyword combines truth tests and short-circuits, so use and for ordinary Boolean conditions.


