Python - Bitwise Operators

Overview

Estimated time: 20–30 minutes

Bitwise operators work on the binary representation of integers. They’re used for flags, masks, low-level protocols, and performance-sensitive code.

Learning Objectives

  • Use &, |, ^, ~, <<, >> correctly.
  • Apply masks to set, clear, and toggle bits.
  • Understand signed vs unsigned shifts and Python’s arbitrary-precision integers.

Prerequisites

  • Basic integer arithmetic and operator precedence

Examples

a = 0b1010  # 10
b = 0b1100  # 12
print(bin(a & b))  # AND -> 0b1000
print(bin(a | b))  # OR  -> 0b1110
print(bin(a ^ b))  # XOR -> 0b0110
print(bin(~a & 0xF)) # NOT masked to 4 bits -> 0b0101

x = 0b0001
x = x << 2         # shift left 2 -> 0b0100
print(bin(x))

FLAGS_READ  = 0b0001
FLAGS_WRITE = 0b0010
flags = 0
flags |= FLAGS_READ        # set READ
print(flags & FLAGS_READ != 0)   # check
flags &= ~FLAGS_READ       # clear READ
flags ^= FLAGS_WRITE       # toggle WRITE
print(bin(flags))

Common Pitfalls

  • ~ (bitwise NOT): Python integers are unbounded; ~x equals -(x+1). Mask to a width when needed, e.g., ~x & 0xFF.
  • Operator precedence: shifts happen before &, which happens before ^ then |; parenthesize to be explicit.

Best Practices

  • Define named constants for flags and keep masks in one place.
  • Prefer enums.IntFlag (3.6+) for readability with sets of flags.

Checks for Understanding

  1. How do you clear a specific bit using a mask?
  2. Why might you mask after ~ in Python?
Show answers
  1. x &= ~MASK
  2. Because Python integers are unbounded; mask to a fixed width (e.g., & 0xFF).

Exercises

  1. Implement a small permissions system using bit flags and helper functions (set/clear/check).
  2. Write a function to pack/unpack bit fields from an integer.