← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 9 of 16

Python Bitwise Operators

Bitwise AND and OR

Bitwise operators act on the individual binary bits of an integer rather than its value as a whole. & (AND) sets each output bit to 1 only where both inputs have a 1 in that position, and | (OR) sets it to 1 if either input does — the same logic gates used in digital electronics, just applied to numbers.

Example: Bitwise AND and OR

python
print(6 & 3)
print(6 | 3)

Bitwise XOR

^ (XOR) sets a bit to 1 only when the corresponding input bits differ — one 1 and one 0 — and to 0 when they match. This property makes XOR useful for toggling bits and for lightweight checksums.

Example: Bitwise XOR

python
print(6 ^ 3)

Bitwise NOT

~ (NOT) is a unary operator that flips every bit of its operand, which mathematically works out to -(x + 1) for any integer x due to how Python represents negative numbers — a detail that surprises people expecting a simple bit-flip on the visible digits.

Example: Bitwise NOT

python
print(~5)

Shift Operators

<< shifts bits left, inserting zeros on the right (equivalent to multiplying by 2 per position shifted), while >> shifts bits right, which is equivalent to integer division by 2 per position — both are fast alternatives to multiplication or division by powers of two.

Example: Shift Operators

python
print(1 << 3)
print(16 >> 2)

Bitwise Flags

Because a single integer holds many bits, programs sometimes pack several true/false flags into one number and use bitwise operators to set, clear, or test individual flags — a compact technique borrowed from lower-level systems programming.

Example: Bitwise Flags

python
READ = 1
WRITE = 2
permissions = READ | WRITE
print(permissions & WRITE != 0)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.