Bitwise operators in Python
Python has the same six bitwise operators as C.
A Python integer has no fixed bit width, so a value never overflows.
That difference changes the result of NOT and of a left shift.
Try bitwise operators in Python in the bit editor
The result of 255 XOR 0x0F. Edit the expression or select a bit to flip it.
7
6
5
4
3
2
1
0
240
value · 8 bits · unsigned
- hex
- 0xF0
The bitwise operators of Python
| Operator | Name | Example | Result |
|---|---|---|---|
| & | AND | 12 & 10 | 8 |
| | | OR | 12 | 10 | 14 |
| ^ | XOR | 12 ^ 10 | 6 |
| ~ | NOT | ~5 | -6 |
| << | Left shift | 1 << 4 | 16 |
| >> | Right shift | 16 >> 2 | 4 |
| & 0xFF | Mask to 8 bits | ~5 & 0xFF | 250 |
Where bitwise operators in Python is used
A test script for a device builds the same register values as the firmware.
A protocol parser reads a field out of a byte with a mask and a shift.
A tool that writes a config blob needs the exact bits the device expects.
Bitwise operators in Python: points to note
- The result of ~5 is -6, not 250. Python has no fixed width, so the value stays negative.
- Apply & 0xFF to see the 8-bit form. The mask gives the value a width.
- A left shift never drops a bit. The integer grows, so 1 << 100 is a valid value.
- A right shift of a negative value keeps the sign, so -8 >> 1 is -4.
- The methods int.bit_count and int.bit_length give the count of bits with the value 1 and the width.
The full bit editor
The full editor holds many values, evaluates expressions across them, and reads live values from a serial port.
Open this value in the full editorQuestions about bitwise operators in Python
- Why does Python print -6 for ~5?
- A Python integer has unlimited width, so NOT gives the true negative value. Apply & 0xFF for the 8-bit form.
- How do I convert an integer to binary in Python?
- Call bin(value) for a string with the 0b prefix, or format(value, "08b") for a fixed width.
- How do I count the bits with the value 1?
- Call value.bit_count() in Python 3.10 or later, or bin(value).count("1") in an earlier version.