Bitwise Operators

Bitwise operators in Python are used to perform operations at the binary (bit) level. They work on integers by converting them into binary representation, applying the operation, and returning the result as an integer.
Bitwise operators are commonly used in:
  • Low-level programming
  • Performance optimization
  • Networking and cryptography
  • Flags and permissions

What Are Bitwise Operators?

Bitwise operators operate on individual bits of integers.
Example:
python
a = 5   # Binary: 0101
b = 3   # Binary: 0011

Bitwise Operators Table

OperatorNameDescription
&ANDSets each bit to 1 if both bits are 1
|ORSets each bit to 1 if at least one bit is 1
^XORSets each bit to 1 if bits are different
~NOTInverts all bits
<<Left ShiftShifts bits left
>>Right ShiftShifts bits right

Bitwise AND (&)

Compares each bit of two numbers.
python
a = 5   # 0101
b = 3   # 0011
print(a & b)
Explanation:
0101 0011 ---- 0001 -> 1

Bitwise OR (|)

Sets a bit if any one bit is 1.
python
a = 5
b = 3
print(a | b)
Explanation:
0101 0011 ---- 0111 -> 7

Bitwise XOR (^)

Sets a bit if bits are different.
python
a = 5
b = 3
print(a ^ b)
Explanation:
0101 0011 ---- 0110 -> 6

Bitwise NOT (~)

Inverts all bits.
python
a = 5
print(~a)
Explanation:
~0101 = -(5 + 1) = -6

Bitwise Left Shift (<<)

Shifts bits to the left (multiplies by powers of 2).
python
a = 5
print(a << 1)
python
print(a << 2)
Explanation:
5 << 1 = 10 5 << 2 = 20

Bitwise Right Shift (>>)

Shifts bits to the right (divides by powers of 2).
python
a = 20
print(a >> 1)
python
print(a >> 2)
Explanation:
20 >> 1 = 10 20 >> 2 = 5

Bitwise Operators with Assignment

python
x = 5
x &= 3
print(x)
python
y = 5
y |= 3
print(y)
python
z = 5
z ^= 3
print(z)

Bitwise Operators vs Logical Operators

Bitwise OperatorsLogical Operators
Works on bitsWorks on Boolean values
Uses &, |, ^, ~Uses and, or, not
No short-circuitingSupports short-circuiting
Operates on integersOperates on Boolean expressions
Used in low-level operationsUsed in conditional logic
python
print(True & False)
python
print(True and False)

Common Use Case: Flags

python
READ = 4   # 100
WRITE = 2  # 010
EXECUTE = 1 # 001

permission = READ | WRITE
print(permission)
python
print(permission & READ)

Common Mistakes

Confusing Logical and Bitwise Operators

python
if a > 0 & b > 0:
    pass
Correct:
python
if a > 0 and b > 0:
    pass

Summary

  • Bitwise operators work at binary level
  • Python supports AND, OR, XOR, NOT, shifts
  • Used for performance and low-level logic
  • Different from logical operators
  • Shifts multiply or divide by powers of two
  • Useful for flags and permissions

Practice

  • Convert numbers to binary and apply bitwise operators
  • Use shift operators to multiply and divide
  • Create a simple permission system using bitwise operators
  • Compare logical and bitwise behavior