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

Python Bitwise Operators

Bitwise operators work on the tiny 0s and 1s that computers use inside, like flipping rows of light switches one by one. They let you check or change individual switches in a number.
Syntax
python
result = a & b  # AND
result = a | b  # OR
result = a ^ b  # XOR
result = ~a
result = a << n  # or >> n

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  # bit 0
WRITE = 2  # bit 1
permissions = READ | WRITE  # combine both flags into one integer
print(permissions & WRITE != 0)  # test whether the WRITE flag is set
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Confusing & and | with and and or; 5 & 3 is a bitwise operation giving 1, not a boolean.
  2. Using ^ as a power operator, when it is bitwise XOR (2 ^ 3 is 1).
  3. Forgetting precedence: a & b == c is parsed as a & (b == c), so write (a & b) == c.

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.