Content · Programming · Python

Python Bitwise Operators: &, |, ^, ~, <<, and >>

Bitwise operations work on integer bit patterns. & keeps shared set bits, | combines them, ^ toggles differing bits, ~ inverts bits according to Python’s infinite two’s-complement model, and shifts move bits left or.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains Bitwise Operators: &, |, ^, ~, <<, and >> through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


Bitwise operations work on integer bit patterns. & keeps shared set bits, | combines them, ^ toggles differing bits, ~ inverts bits according to Python’s infinite two’s-complement model, and shifts move bits left or right.

When You Would Use This


Use a feature mask where individual bits represent enabled settings.

Step-by-Step Example


READ_PERMISSION = 0b001
WRITE_PERMISSION = 0b010
EXECUTE_PERMISSION = 0b100
user_permissions = READ_PERMISSION | WRITE_PERMISSION
print(bin(user_permissions))
print(bool(user_permissions & WRITE_PERMISSION))
print(user_permissions << 1)

How the Example Works


The combined mask is 0b11. AND tests whether the write bit is present, returning a nonzero result. Shifting left once doubles a nonnegative integer bit pattern.

Example Output


0b11
True
6

Try It Yourself


Add execute permission to the mask and test for it.

Common Beginner Mistakes


  • Confusing bitwise & and bitwise OR with short-circuit and and or.
  • Using ^ for exponentiation.
  • Assuming ~x flips only a fixed number of bits without accounting for Python’s negative integer representation.

Key Takeaways


  • Bitwise operations work on integer bit patterns.
  • The combined mask is 0b11.
  • Avoid this mistake: Confusing bitwise & and bitwise OR with short-circuit and and or.
Share this resourceSend this page to someone who may find it useful.