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
| Operator | Name | Description |
|---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Sets each bit to 1 if at least one bit is 1 |
^ | XOR | Sets each bit to 1 if bits are different |
~ | NOT | Inverts all bits |
<< | Left Shift | Shifts bits left |
>> | Right Shift | Shifts 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 Operators | Logical Operators |
|---|---|
| Works on bits | Works on Boolean values |
Uses &, |, ^, ~ | Uses and, or, not |
| No short-circuiting | Supports short-circuiting |
| Operates on integers | Operates on Boolean expressions |
| Used in low-level operations | Used 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