the full guide

Bitwise operators

Bitwise operators work on the individual binary digits (bits) of integers: AND (&), OR (|), XOR (^), NOT (~), left shift (<<) and right shift (>>).

8 min Intermediate

What you need: The earlier topics of this module.

Definition

Bitwise operators work on the individual binary digits (bits) of integers: AND (&), OR (|), XOR (^), NOT (~), left shift (<<) and right shift (>>).

In simple words

A number in binary is a row of switches, either on or off. 5 is 101. Bitwise operators flip and combine these switches directly, one position at a time.

Why it matters

They appear in permissions, flags, compression, networking and image masks. NumPy and pandas also use & and | to combine conditions on columns.

How it works

OperatorRule5 and 3
&1 if both bits are 1101 & 011 = 001 = 1
|1 if either bit is 1101 | 011 = 111 = 7
^1 if the bits differ101 ^ 011 = 110 = 6
~Flips all bits~5 = −6
<<Shift left: multiply by 2 per step5 << 1 = 10
>>Shift right: floor divide by 2 per step5 >> 1 = 2

In code

bits.py
a, b = 5, 3
print(bin(a), bin(b))
print("AND:", a & b)
print("OR:", a | b)
print("XOR:", a ^ b)
print("Shift left:", a << 1)

READ, WRITE, RUN = 4, 2, 1
permission = READ | RUN
print("Can write?", bool(permission & WRITE))
print("Can read?", bool(permission & READ))

Output

0b101 0b11
AND: 1
OR: 7
XOR: 6
Shift left: 10
Can write? False
Can read? True

Common mistakes

  • Using and/or on NumPy or pandas conditions. Use & and | with brackets: (a > 1) & (b < 2).
  • Confusing & with and. & works on bits, and and works on truth values.

Check yourself

Question 1

1. What is 6 & 3?

Question 2

2. What is 4 << 2?

Summary

  • Bitwise operators work on binary digits.
  • Shifting left doubles, and shifting right halves.
  • Pandas conditions use & and |.

Finished reading?

Sources: The Python Tutorial, python.org