Python Bitwise Operators

Bitwise operators are used to perform operations on individual bits of binary numbers. In Python, these operators work on integers, treating them as strings of binary digits (0s and 1s).

While rarely used in everyday web development, they are crucial for low-level programming, cryptography, image processing, and optimizing memory-constrained applications.

List of Bitwise Operators

OperatorNameDescriptionExample (a=10, b=4)
&ANDSets each bit to 1 if both bits are 1a & b (Result: 0)
|ORSets each bit to 1 if one of two bits is 1a | b (Result: 14)
^XORSets each bit to 1 if only one of two bits is 1a ^ b (Result: 14)
~NOTInverts all the bits (yields -(x+1))~a (Result: -11)
<<Left ShiftShift left by pushing zeros from the righta << 2 (Result: 40)
>>Right ShiftShift right by pushing copies of the leftmost bita >> 2 (Result: 2)

1. Bitwise AND, OR, and XOR

These operators compare each bit of the first operand with the corresponding bit of the second operand.

Python
a = 10  # Binary: 1010
b = 4   # Binary: 0100

# Bitwise AND
print(a & b)  # Output: 0 (Binary: 0000)

# Bitwise OR
print(a | b)  # Output: 14 (Binary: 1110)

# Bitwise XOR
print(a ^ b)  # Output: 14 (Binary: 1110)

2. Bitwise Shift Operators

Shifting moves the bit pattern to the left or right. This is mathematically equivalent to multiplying or dividing by powers of 2.

  • Left Shift (<<): Multiplies number by 2 for every shift.
  • Right Shift (>>): Performs floor division by 2 for every shift.
Python
x = 5  # Binary: 0000 0101

# Left Shift: 5 * (2^2) = 20
print(x << 2)  # Binary: 0001 0100 -> Output: 20

# Right Shift: 5 // (2^1) = 2
print(x >> 1)  # Binary: 0000 0010 -> Output: 2

3. Bitwise NOT (~)

The NOT operator inverts the bits. In Python, because integers are signed, ~x is calculated as -(x + 1).

Python
print(~10) # Output: -11
print(~-5) # Output: 4

4. Practical Use Cases

Bitwise operators are highly efficient. Here is where you might see them in professional code:

ApplicationOperator UsedBenefit
Permission Systems| , &Store multiple flags (Read, Write, Exec) in one integer
Color Manipulation>> , &Extracting R, G, B values from a Hex color code
Data Compression<< , >>Packing multiple small values into a single byte
Odd/Even Check& 1Faster than using the modulo (%) operator
Python
num = 7
if num & 1:
    print('Odd')
else:
    print('Even')