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
| Operator | Name | Description | Example (a=10, b=4) |
|---|---|---|---|
| & | AND | Sets each bit to 1 if both bits are 1 | a & b (Result: 0) |
| | | OR | Sets each bit to 1 if one of two bits is 1 | a | b (Result: 14) |
| ^ | XOR | Sets each bit to 1 if only one of two bits is 1 | a ^ b (Result: 14) |
| ~ | NOT | Inverts all the bits (yields -(x+1)) | ~a (Result: -11) |
| << | Left Shift | Shift left by pushing zeros from the right | a << 2 (Result: 40) |
| >> | Right Shift | Shift right by pushing copies of the leftmost bit | a >> 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.
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.
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).
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:
| Application | Operator Used | Benefit |
|---|---|---|
| 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 | & 1 | Faster than using the modulo (%) operator |
num = 7
if num & 1:
print('Odd')
else:
print('Even')
Codecrown