Sub topic 16
Bitwise Operators and Shifts
Bitwise operators work on the binary digits of integers. This chapter assumes you know how Python's int type works and can read binary literals like 0b0101. It also assumes you know the general idea of operator precedence. You will learn each operator, how negative numbers behave, and common bit-manipulation patterns. You will also learn the precedence traps.
The operators
| Operator | Name | Result bit is 1 when | Column |
|---|---|---|---|
| `a & b` | AND | both bits are 1 | |
| `a \ | b` | OR | at least one bit is 1 |
| `a ^ b` | XOR | the bits differ | |
| `~a` | NOT (invert) | the bit is 0 | |
| `a << n` | left shift | bits move left by `n`, zeros fill in | |
| `a >> n` | right shift | bits move right by `n`, low bits are dropped |
These operators accept integers only. 1.5 & 1 raises TypeError. Convert with int() first if you need to.
flags = 0b0101
print(flags & 0b0100)
print(flags | 0b0010)
print(flags ^ 0b0001)
print(1 << 3)
print(~5)This prints 4, 7, 4, 8 and -6. Use bin() or a format spec to see the bits:
x = 0b0101
print(bin(x))
print(f"{x:08b}")
print(f"{x:#010b}")
print(f"{0xFF:08b}")Negative numbers
Python integers have unlimited size. The bitwise operators behave as if a negative number had an infinite run of leading 1 bits (two's complement). Two rules follow from this:
~xalways equals-x - 1. That is why~5is-6.bin()shows the sign and magnitude (bin(-5)is'-0b101'), not the underlying bits.
To see a fixed-width view of a negative number, mask it:
print(bin(-5))
print(-5 & 0xFF)
print(f"{-5 & 0xFF:08b}")The second line prints 251. The third prints 11111011, the 8-bit two's complement form of -5.
Shifts
x << n multiplies by 2 ** n. x >> n floor-divides by 2 ** n. Because the integer has no fixed width, a left shift never overflows.
print(3 << 4)
print(1 << 100)
print(-8 >> 1)
print(-7 >> 1)
print(-1 >> 10)The output is 48, a 31-digit integer, -4, -4, and -1. A right shift rounds toward negative infinity, so -7 >> 1 is -4, not -3. This matches //: -7 // 2 is also -4. A right shift of -1 stays -1 forever.
A negative shift count raises ValueError: negative shift count.
try:
1 << -1
except ValueError as e:
print(e)Common patterns
Each pattern combines a mask with one operator. Here n is the bit position, counted from 0 at the right.
| Task | Expression | Column |
|---|---|---|
| Test bit `n` | `x & (1 << n)` is nonzero | |
| Set bit `n` | `x \ | (1 << n)` |
| Clear bit `n` | `x & ~(1 << n)` | |
| Toggle bit `n` | `x ^ (1 << n)` | |
| Keep the low 8 bits | `x & 0xFF` | |
| Is a positive `n` a power of two | `n & (n - 1) == 0` |
Permission flags
Flags store several yes/no options in one integer. Each option gets its own bit.
READ = 0b001
WRITE = 0b010
EXEC = 0b100
perm = READ | WRITE
print(bool(perm & WRITE))
perm &= ~WRITE
print(f"{perm:03b}")
perm ^= EXEC
print(f"{perm:03b}")The output is True, then 001, then 101. The augmented forms &=, |=, ^=, <<= and >>= all exist.
For named flags in larger programs, enum.IntFlag gives you these same operators with readable names.
Packing and unpacking fields
Shifts and masks let you store several small values in one integer. This example packs an RGB colour.
r, g, b = 255, 128, 0
color = (r << 16) | (g << 8) | b
print(hex(color))
print((color >> 16) & 0xFF)
print((color >> 8) & 0xFF)
print(color & 0xFF)The packed value is 0xff8000. To unpack a field, shift it down to the right edge, then mask off everything above it.
Counting bits
n = 0b10110
print(n.bit_length())
print(n.bit_count())bit_length() is the number of bits needed to represent the number (5 here). bit_count() counts the 1 bits (3 here). bit_count() requires Python 3.10 or later. On older versions, use bin(n).count("1").
Precedence
Python's bitwise operators bind tighter than comparisons. This differs from C, where x & 1 == 0 parses as x & (1 == 0). From higher to lower precedence, the order is:
Three consequences follow:
n & 1 == 0parses as(n & 1) == 0, which is usually what you want.- Shifts bind looser than
+, so1 << 2 + 1is1 << 3, which is 8. &,^and|bind tighter thanand/or, but they are not substitutes for them.
n = 6
print(n & 1 == 0)
print(1 << 2 + 1)
print((1 << 2) + 1)This prints True, 8 and 5. Add parentheses whenever you mix bitwise operators with arithmetic. Readers rarely remember this table.
Gotchas
Bitwise operators are not logical operators
& evaluates both operands and works on bits. and short-circuits and works on truthiness. They can give different answers:
print(1 and 2)
print(1 & 2)The first prints 2 and the second prints 0, because 0b01 & 0b10 shares no bits. Chained comparisons make mistakes worse: x > 1 & y < 5 parses as x > (1 & y) < 5, which is almost never what you meant. Write x > 1 and y < 5.
Booleans and sets
bool is a subclass of int. True & False returns False, a bool. True & 1 returns 1, an int. Between two bool values, &, | and ^ work as non-short-circuiting logic.
Sets reuse the same symbols for set operations: {1, 2} | {2, 3} is the union, & is the intersection, ^ is the symmetric difference, and - is the difference. From Python 3.9, dict | dict merges dictionaries.
`~` on booleans
~True is -2, not False, because True is the integer 1. Use not for boolean negation.
print(~True)
print(not True)Exercise
What do -9 >> 1, ~0 and 0b1100 ^ 0b1010 evaluate to? Then write an expression that clears bit 2 of x and leaves other bits unchanged.
Show answer
-9 >> 1 is -5, because right shift floors -4.5 to -5. ~0 is -1, since ~x equals -x - 1. 0b1100 ^ 0b1010 is 0b0110, which is 6. To clear bit 2, use x & ~(1 << 2).
Exercise
Why does x > 1 & y < 5 not test two conditions, and how do you fix it? Also, given n = 0b1011_0110, write an expression that extracts the high 4 bits as an integer.
Show answer
Bitwise & binds tighter than the comparison operators, so the expression parses as the chained comparison x > (1 & y) < 5. Fix it with x > 1 and y < 5. The high nibble is (n >> 4) & 0xF, which gives 0b1011, or 11.