PythonPython Operators and ExpressionsPython bitwise operators
What are bitwise operators?
Question 45 of 88 · Updated
On this page
- 1. The six bitwise operators
- 2. Understanding binary digits
- 3. Left and right shifts
- 4. Negative numbers and bitwise inversion
- 5. Bit masks: set, clear, toggle and test
- 6. Testing any flag versus all flags
- 7. Practical example: pack two four-bit fields into one byte
- 8. Counting bits and testing powers of two
- 9. Named flags using IntFlag
- 10. Other types can use bitwise syntax
- 11. Bitwise operators versus logical operators
- 12. Precedence and common mistakes
- Frequently asked questions
- What is the difference between bitwise AND and logical AND?
- Why does ~5 return -6?
- Can bitwise operators be used on floats?
- What is a bit mask?
- Are bitwise operations always O(1)?
- Interview-ready answer
- Official references
Bitwise operators act on the binary representation of integers. Python supports bitwise AND (&), OR (|), XOR (^), inversion (~), left shift (<<) and right shift (>>). They are useful for manipulating flags, extracting fields from packed data, working with binary formats and implementing algorithms that depend on individual bits.
Unlike logical operators, integer bitwise operations operate on corresponding bit positions rather than deciding whether a whole object is truthy.
1. The six bitwise operators#
| Operator | Meaning | Example | Result |
|---|---|---|---|
& | AND: both bits set | 12 & 10 | 8 |
| `\ | | OR: at least one bit set | `12 \ |
^ | XOR: exactly one bit set | 12 ^ 10 | 6 |
~ | Inversion: complement all bits | ~12 | -13 |
<< | Left shift | 5 << 2 | 20 |
>> | Right shift | 20 >> 2 | 5 |
PYTHONprint(12 & 10, 12 | 10, 12 ^ 10, ~12)
Output:
8 14 6 -13The examples use ordinary Python integers. Other types may implement these symbols with different meanings.
2. Understanding binary digits#
Each position in a nonnegative binary integer represents a power of two. For example, binary 1100 is 8 + 4 = 12, and binary 1010 is 8 + 2 = 10.
Python supports binary literals with a 0b prefix. The format function can produce a binary string with a specified minimum width.
PYTHONprint(format(12,"04b"), format(10,"04b"), format(12 & 10,"04b"))
Output:
1100 1010 1000The formatting width is not an integer storage width. Python integers have arbitrary precision, subject to memory and implementation limits.
For individual bits, the following truth table gives the three binary bitwise operations.
| A | B | AND | OR | XOR |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
The bitwise AND of 1100 and 1010 is 1000. OR produces 1110, and XOR produces 0110. These are binary representations of 8, 14 and 6.
The four branches represent positions from the most significant displayed bit to the least significant bit. The diagram illustrates the mathematical operation, not an implementation's CPU instructions or scheduling.
3. Left and right shifts#
For an integer x and a nonnegative integer shift count n, x << n is mathematically equivalent to x multiplied by 2n. The operation x >> n is equivalent to floor division by 2n.
PYTHONprint(5 << 2, 20 >> 2, -5 >> 1, -5 // 2)
Output:
20 5 -3 -3Left shifting binary 101 by two positions produces binary 10100. Right shifting binary 10100 by two positions returns binary 101.
For negative integers, right shift follows floor division rather than truncation toward zero. For example, -5 >> 1 returns -3, not -2.
Python does not provide a separate unsigned right-shift operator. If an application needs to interpret a value as an unsigned integer of a specified width, explicitly mask it to that width before shifting.
Negative shift counts raise ValueError. Large left shifts may allocate large integers, so validate untrusted shift counts and width parameters.
4. Negative numbers and bitwise inversion#
Python defines integer bitwise operations as though performed using two's-complement representation with infinitely many sign bits. This is a semantic model, not a claim that Python physically stores infinitely many bits.
For an ordinary integer x, the identity ~x = -(x + 1) always holds.
PYTHONprint(bin(-5), ~5, -5 & 255, (~5) & 255)
Output:
-0b101 -6 251 250The bin function displays a minus sign for a negative integer; it does not return a fixed-width two's-complement representation.
The number 255 is the eight-bit mask 11111111. Applying & 255 retains the lowest eight bits of a value. Therefore -5 & 255 produces 251, the unsigned interpretation of -5 modulo 256. Similarly, (~5) & 255 returns 250, corresponding to the eight-bit complement of 00000101.
To obtain a complement limited to w bits, use (~x) & ((1 << w) - 1) for a validated positive integer width w. Without the mask, inversion does not restrict the result to w bits.
This distinction is important when transferring algorithms from languages that use fixed-width signed or unsigned integers. Python's unlimited-width integer semantics do not automatically reproduce overflow, unsigned shifts or register-sized inversion.
5. Bit masks: set, clear, toggle and test#
A bit mask is an integer whose set bits select positions of interest. Bit indexes usually begin at zero for the least significant bit. The mask for position k is 1 << k.
| Goal | Expression |
|---|---|
| Set selected bits | `flags \ |
| Clear selected bits | flags & ~mask |
| Toggle selected bits | flags ^ mask |
| Check whether any selected bit is set | bool(flags & mask) |
| Check whether every selected bit is set | (flags & mask) == mask |
PYTHONflags = 0b0101 mask = 1 << 1 flags |= mask print(format(flags,"04b")) flags &= ~mask print(format(flags,"04b")) flags ^= 1 << 2 print(format(flags,"04b")) print(bool(flags & 1))
Output:
0111
0101
0001
TrueThe first update sets bit 1, the next clears bit 1, and the third toggles bit 2. The final test checks bit 0.
Setting a bit that is already set leaves it unchanged. Clearing an already-clear bit also leaves it unchanged. XOR toggles a selected bit each time, so applying the same toggle twice restores the original value.
These operations produce new integer values; integers are immutable. Augmented assignment rebinds the target to the result for ordinary ints.
6. Testing any flag versus all flags#
When a mask represents several positions, the distinction between any and all is essential.
PYTHONREAD, WRITE, EXEC = 1, 2, 4 flags = READ | EXEC required = READ | WRITE print(bool(flags & required), (flags & required) == required)
Output:
True FalseThe flags value includes READ but not WRITE. At least one required bit is present, so the first test is True. Not all required bits are present, so the second is False.
Checking all bits of an empty mask returns True, while checking whether any bit of an empty mask is present returns False. Choose the desired policy explicitly if empty requirements are invalid for the application.
This example represents local flag mathematics, not a complete authorization system. Actual access decisions must use trusted permission data and appropriate server-side enforcement.
7. Practical example: pack two four-bit fields into one byte#
A nibble is a four-bit field. Two unsigned nibbles can represent the high and low portions of an eight-bit byte.
PYTHONdef pack(high, low): if not (0 <= high <= 15 and 0 <= low <= 15): raise ValueError("nibbles must be in 0..15") return (high << 4) | low def unpack(byte): if not 0 <= byte <= 255: raise ValueError("byte must be in 0..255") return byte >> 4, byte & 15 value = pack(10, 5) print(hex(value), unpack(value)) assert all(unpack(pack(a,b)) == (a,b) for a in range(16) for b in range(16))
Output:
0xa5 (10, 5)The example assumes integer inputs and validates their numeric ranges. A public interface should also enforce the intended integer-type contract, including whether Boolean values are accepted.
The high nibble 1010 moves into positions 4–7. The low nibble 0101 occupies positions 0–3. OR combines the disjoint fields into 10100101, hexadecimal A5. The unpack function extracts the high part by shifting and the low part by masking with 15 (binary 1111).
The assertion checks every combination of two four-bit unsigned fields: 16 × 16 = 256 possible inputs. This exhaustive test confirms that packing and unpacking invert each other within the stated domain.
For fixed eight-bit fields, the operations require constant-size arithmetic. In a larger serialization protocol, field sizes, endianness, signedness and validation must be specified. Prefer standard-library struct or int.to_bytes and int.from_bytes where those APIs express the format more clearly.
8. Counting bits and testing powers of two#
Python's int type provides bit_length() and bit_count(). bit_length returns the number of bits necessary to represent the absolute value without leading zeros; bit_count returns the number of ones in the binary representation of the absolute value. bit_count was added in Python 3.10.
PYTHONprint((40).bit_length(), (40).bit_count(), (-40).bit_count()) print([n for n in range(10) if n > 0 and (n & (n-1)) == 0])
Output:
6 2 2
[1, 2, 4, 8]Binary 40 is 101000, which has six positions and two set bits.
For a positive integer n, n & (n-1) clears its lowest set bit. If the result is zero, n had exactly one set bit and is a power of two. The n > 0 condition is required: zero also produces zero in the bitwise expression but is not a power of two.
The time complexity of scanning n bounded-size integers is O(n) under the usual fixed-size arithmetic model. Python's arbitrary-precision operations do not have universally constant cost. Bitwise operations, shifts and bit counts depend on operand sizes and, in the case of left shifts, the resulting integer size.
9. Named flags using IntFlag#
For a fixed collection of named bit flags, the standard library offers enum.IntFlag. This can express intent more clearly than repeated numeric masks.
PYTHONfrom enum import IntFlag class Permission(IntFlag): READ=1 WRITE=2 EXECUTE=4 p=Permission.READ | Permission.WRITE print(int(p), bool(p & Permission.EXECUTE))
Output:
3 FalseEach flag occupies a distinct bit position. The bitwise OR combines the selected members, while the AND test determines whether the execute flag is present.
Validate incoming masks according to the allowed-bit policy. A raw integer may contain unknown bits, and different enumeration boundary settings can handle those values differently. IntFlag alone does not provide authorization or validate untrusted input against all application rules.
10. Other types can use bitwise syntax#
PYTHONa={1,2}; b={2,3} print(sorted(a & b), sorted(a | b), sorted(a ^ b)) print({"a":1} | {"a":2,"b":3})
Output:
[2] [1, 2, 3] [1, 3]
{'a': 2, 'b': 3}For sets, & means intersection, OR means union, and XOR means symmetric difference. Dictionaries support union syntax from Python 3.9; for overlapping keys, the right operand's value wins in the demonstrated operation.
These operations are not integer bit manipulation. Python selects behavior according to operand types and their supported special methods. Their performance depends on the relevant data structures and implementation.
11. Bitwise operators versus logical operators#
PYTHONdef right(): print("evaluated") return True print(False and right()) print(False & right())
Output:
False
evaluated
FalseThe logical and expression does not call right because the left operand is false. The bitwise & expression evaluates both operands before applying the operation.
For bool operands, & can produce Boolean results similar to logical conjunction, but the evaluation semantics are different. Do not replace logical and/or with bitwise operations in conditions merely because some truth-table outputs coincide.
For ordinary integer operands, bitwise operators act on bits rather than returning one of the operands according to truthiness. Inversion of bool using ~ is deprecated starting in Python 3.12; use not for logical negation.
12. Precedence and common mistakes#
Shifts bind less tightly than addition and subtraction. Bitwise AND binds more tightly than XOR, which binds more tightly than bitwise OR. These bitwise binary operations bind more tightly than comparisons, while comparisons bind more tightly than logical and and or.
Write masks with parentheses when combining different operators. For example, (flags & required) == required clearly communicates the intended all-flags test.
Four independently executed error cases illustrate unsupported operations:
| Expression | Expected exception |
|---|---|
1 << -1 | ValueError |
1.5 & 1 | TypeError |
| `1 \ | "2"` |
~1.0 | TypeError |
Common mistakes include confusing ^ with exponentiation, treating ~x as a fixed-width complement, using a nonpositive value in a power-of-two test, testing any bit when all bits are required, and assuming shifts always outperform ordinary multiplication or division.
Choose clear operators based on semantics first. For optimization, measure actual workloads with representative operand sizes.
Frequently asked questions#
What is the difference between bitwise AND and logical AND?#
Bitwise AND operates on corresponding integer bits and evaluates both operand expressions. Logical and tests the truth of its left operand and evaluates the right operand only if necessary.
Why does ~5 return -6?#
Python's integer complement follows ~x = -(x+1), consistent with infinitely sign-extended two's-complement semantics. An explicitly masked eight-bit complement gives 250.
Can bitwise operators be used on floats?#
Ordinary float values do not support integer bitwise operations. Use an appropriate integer representation when bit manipulation is actually required.
What is a bit mask?#
A bit mask is an integer identifying selected bit positions. It can be used to set, clear, toggle, extract or test those positions.
Are bitwise operations always O(1)?#
No. Fixed-size integer calculations are often modeled as constant-time operations, but Python integers have arbitrary precision and operation costs can grow with operand and output sizes.
Interview-ready answer#
Python bitwise operators manipulate integer bits: & computes AND, OR selects bits set in either operand, ^ computes XOR, ~ complements all bits, << shifts left and >> shifts right. Python uses semantics equivalent to infinitely sign-extended two's-complement integers, so ~x equals -(x+1) and right shifts of negative integers follow floor division. Bit masks enable setting, clearing, toggling and testing individual bits, and shifts combined with masks can pack and unpack binary fields. Unlike logical operators, bitwise operators do not short-circuit. Other data types may overload the same symbols for different operations.
Official references#
- Python Standard Library — Bitwise Operations on Integer Types
- Python Standard Library — Additional Methods on Integer Types
- Python Language Reference — Shifting operations
- Python Language Reference — Binary bitwise operations
- Python Language Reference — Boolean operations
- Python Standard Library — enum.IntFlag
- Python Standard Library — Boolean Type
Verification note: Eleven independent output tests and four expected-exception tests passed on CPython 3.13.5. All 256 valid nibble-packing round trips were checked. The three fenced Mermaid diagrams were manually reviewed for syntax, bit arithmetic and instructional value. The local Mermaid package and CLI were unavailable, so parser-level validation and website rendering were not performed. Official reference links are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.
- 2.Python Language Reference — Shifting operationsdocs.python.org
- 3.Python Standard Library — enum.IntFlagdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design