Featurecore
Bitwise and shift operators
Also called Python bitwise operators, bitwise and, bitwise or, xor operator, left shift, right shift, invert operator.
Python's bitwise operators &, |, ^ and ~ and its shifts << and >> work on integers as if in two's complement with infinite sign bits. They bind looser than arithmetic and tighter than comparisons.
- Language
- Python
Synopsis
a, b = 0b1100, 0b1010
print(bin(a & b), bin(a | b), bin(a ^ b))
print(~a, a << 2, a >> 2)
0b1000 0b1110 0b110
-13 48 3
Semantics
r1. Bitwise operations make sense only for integers, and the result is computed "as though carried out in two's complement with an infinite number of sign bits".1 Example: negative-bits.
r2. & gives the bitwise AND, ^ the bitwise XOR and | the bitwise OR of two integers. A custom class can support them with __and__(), __xor__() and __or__() and their reflected forms.2 Example: bit-ops.
r3. x << n and x >> n shift x by n bits. "A right shift by n bits is defined as floor division by" pow(2,n), and a left shift by n bits is multiplication with pow(2,n).3 Since integers have unlimited precision, a left shift never overflows.4 Example: big-shift.
r4. "Negative shift counts are illegal and cause a" ValueError.1 Example: negative-shift.
r5. The unary ~ gives the bitwise inversion of an integer, defined as -(x+1). It has the same priority as unary - and +. An argument of the wrong type raises TypeError.5 Example: bit-ops.
r6. The binary bitwise operators have priorities "lower than the numeric operations and higher than the comparisons".1 The shifts bind tighter than &, & tighter than ^, and ^ tighter than |.2 3 Example: bit-precedence.
r7. Applied to two bools, &, | and ^ return a bool that matches and, or and xor, but the docs prefer and, or and !=. The 3.12 release deprecated ~ on a bool, and the docs say it will raise an error in Python 3.16.6 Example: bool-bits.
r8. Sets reuse the symbols: | is the union, & the intersection and ^ the symmetric difference.7 For dicts, d | other makes a new dict whose values from other win on shared keys; this operator needs Python 3.9 or later.8 Example: sets-and-dicts.
Examples
Infinite sign bits (rule r1): a right shift of a negative number stays negative, and a mask cuts a negative number down to a fixed width.
print(-1 >> 10, -7 >> 1, -7 // 2, ~0)
print(-5 & 0xFF, bin(-5 & 0xFF))
-1 -4 -4 -1
251 0b11111011
Shifts are exact on big integers (rule r3).
big = 1 << 100
print(big, big.bit_length(), big >> 98)
1267650600228229401496703205376 101 4
Permission flags: set a bit with |, test it with &, clear it with & ~, and toggle it with ^.
READ, WRITE, EXEC = 4, 2, 1
mode = READ | WRITE
print(mode, bool(mode & WRITE), bool(mode & EXEC))
mode &= ~WRITE
print(mode)
mode ^= EXEC
print(mode, bin(mode))
6 True False
4
5 0b101
The priorities of rule r6: 6 & 3 == 2 groups as (6 & 3) == 2.
print(6 & 3 == 2, 1 | 2 ^ 3 & 1, 1 | (2 ^ (3 & 1)))
True 3 3
Bitwise operators on bools (rule r7).
print(True & False, True | False, True ^ True)
print(type(True & True).__name__)
False True False
bool
The set and dict forms (rule r8).
a, b = {1, 2, 3}, {2, 3, 4}
print(a | b, a & b, a ^ b)
print({"x": 1, "y": 2} | {"y": 20, "z": 3})
{1, 2, 3, 4} {2, 3} {1, 4}
{'x': 1, 'y': 20, 'z': 3}
Pitfalls
^ is not the power operator
^ is XOR, so 2 ^ 3 is 1. Use ** for a power.
This code runs but gives a wrong answer on purpose.
print(2 ^ 3, 2 ** 3)
1 8
A shift binds looser than +
Arithmetic happens first (rule r6), so 1 << 2 + 1 is 1 << 3.
This code runs but gives a wrong answer on purpose.
print(1 << 2 + 1, (1 << 2) + 1)
8 5
Negative shift counts
A negative count raises ValueError (rule r4). Shift the other way instead.
This code raises ValueError, on purpose.
print(1 << -1)
Floats have no bits
The bitwise operators reject a float (rules r1 and r2). Convert with int() first.
This code raises TypeError, on purpose.
print(3.0 & 1)
Comparison
Go puts <<, >> and & in the same precedence level as *, and | and ^ with +.9 So in Go 1 + 2 << 1 is 1 + (2 << 1), while in Python it is (1 + 2) << 1 (rule r6). Go writes the bitwise complement as the unary ^x, and a negative shift count at run time causes a panic.10 Python uses ~x (rule r5) and raises ValueError (rule r4).
References
- Built-in Types, Python 3.15 documentation, Bitwise Operations on Integer Types
- The Python Language Reference, Python 3.15, 6.9 Binary bitwise operations
- The Python Language Reference, Python 3.15, 6.8 Shifting operations
- Built-in Types, Python 3.15 documentation, Numeric Types, int, float, complex
- The Python Language Reference, Python 3.15, 6.6 Unary arithmetic and bitwise operations
- Built-in Types, Python 3.15 documentation, Boolean Type, bool
- Built-in Types, Python 3.15 documentation, Set Types, set, frozenset
- Built-in Types, Python 3.15 documentation, Mapping types, dict, frozendict
- The Go Programming Language Specification, Operator precedence
- The Go Programming Language Specification, Arithmetic operators
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 8SRX65 Edit this page History Report an error Markdown