Course contentsShow
← Python
Lesson 46 of 1,0601. Foundations and EnvironmentFree lesson

Integer Bitwise Operations and Distinguishing Them From Boolean Logic

Master bitwise AND, OR, XOR, NOT, and shifts to manipulate binary data while avoiding confusion with logical operators.

In this lesson, you will learn how to manipulate the individual binary digits (bits) of an integer and understand why these operations are fundamentally different from logical comparisons.

The Binary Foundation

While you are used to treating integers as whole numbers, Python sees them under the hood as sequences of 1s and 0s. Bitwise operators allow you to look inside an integer and change those bits directly.

  • AND (&): Compares each bit; results in 1 only if both bits are 1.
  • OR (|): Results in 1 if at least one bit is 1.
  • XOR (^): Results in 1 if the bits are different.
  • NOT (~): Flips every bit (0 becomes 1, 1 becomes 0).
  • Shifts (<< or >>): Slides bits to the left or right, effectively multiplying or dividing by powers of two.

Bitwise vs. Boolean: Don’t Mix Them Up!

It is common to confuse bitwise operators (&, |) with logical operators (and, or). Remember this: Logical operators check the "truthiness" of entire objects, while bitwise operators perform math on the binary representation of numbers.

# Boolean Logic (Compares truth values)
print(5 and 3)  # Result: 3 (Because both are truthy)

# Bitwise Logic (Compares binary: 101 & 011)
# 101 (decimal 5)
# 011 (decimal 3)
# ---
# 001 (decimal 1)
print(5 & 3)    # Result: 1

In the example above, 5 and 3 looks at the entire integers as Boolean values. 5 & 3, however, looks at the binary bits 101 and 011. It compares the first position, the second position, and the third position individually.

Because bitwise operators treat integers as physical patterns of bits rather than abstract "true" or "false" values, using them where you intend to write logic checks (like inside an if statement) will often lead to confusing bugs. Always use and/or for conditions, and save &/| for when you specifically need to manipulate the binary structure of your numbers.

Key Takeaway: Logical operators evaluate truth values for control flow, while bitwise operators perform binary-level arithmetic on integer bits.