Sub topic 16
Bitwise operators and shifts
This chapter assumes you know Python's int type, how to write binary literals such as 0b0101, and how print shows values. Bitwise operators work on the binary digits of integers, one position at a time.
The operators
| Operator | Name | Result bit is 1 when | Column |
|---|---|---|---|
| `&` | AND | both bits are 1 | |
| `\ | ` | OR | at least one bit is 1 |
| `^` | XOR | the bits differ | |
| `~` | NOT | the bit is 0 (inverts every bit) | |
| `<<` | left shift | bits move left, zeros fill in | |
| `>>` | right shift | bits move right, the sign is kept |
They apply only to integers (and bool, which is a subtype of int). Using them on a float raises a TypeError.
Worked example
flags = 0b0101
print(flags & 0b0100)
print(flags | 0b0010)
print(flags ^ 0b0001)
print(1 << 3)
print(~5)This prints 4, 7, 4, 8 and -6.
0101 & 0100keeps only the bit set in both, giving0100, which is 4.0101 | 0010sets the second bit as well, giving0111, which is 7.0101 ^ 0001flips the lowest bit, giving0100, which is 4.1 << 3moves the 1 three places left, giving1000, which is 8.
Why `~5` is -6
Python integers behave as if they had an unlimited number of leading sign bits (two's complement). Inverting every bit of a number n gives -n - 1. So ~5 is -6, and ~0 is -1. The result is not a "5-bit" flip, because Python has no fixed width for int.
Shifts as multiplication
Shifting left by k multiplies by 2 ** k. Shifting right by k floors the division by 2 ** k.
print(5 << 2)
print(20 >> 2)
print(-7 >> 1)The output is 20, 5 and -4. The last line matches -7 // 2, because right shift rounds toward negative infinity, just as floor division does.
Using bits as flags
A common use is packing several on/off options into one integer. Each option gets its own bit.
READ = 0b001
WRITE = 0b010
EXEC = 0b100
perms = READ | WRITE
print(bool(perms & WRITE))
print(bool(perms & EXEC))
perms &= ~WRITE
print(perms)This prints True, False and 1. Use | to turn a flag on, & ~flag to turn it off, ^ to toggle it, and & to test it. The augmented forms |=, &=, ^=, <<= and >>= work like +=.
Common errors
- Writing
&or|when you meanandoror. The bitwise versions do not short-circuit and have different precedence. - Forgetting that
&,|and^bind more loosely than comparisons are not the case here: they bind tighter than comparisons, but looser than arithmetic. Inx & 1 == 0, Python readsx & (1 == 0)? No. Comparisons bind looser than&, so it is(x & 1) == 0. Add parentheses anyway for readability. - Shifting by a negative amount raises
ValueError.
Exercise
What does (0b1100 ^ 0b1010) >> 1 print, and why?
Show answer
It prints 3. XOR gives 0b0110 (6), because the bits differ in the two middle positions. Shifting right by one floors 6 / 2, giving 3.