What are Bitwise Operators?
Bitwise operators in Python let you manipulate bits directly! They are like tiny switches that control 1s and 0s. Imagine you are a hacker in the Matrix, flipping bits like a pro!
Python provides six bitwise operators:
Operator | Symbol | Meaning |
---|---|---|
AND | & |
Sets each bit to 1 if both bits are 1 |
OR | ` | ` |
XOR | ^ |
Sets each bit to 1 if only one bit is 1 (not both) |
NOT | ~ |
Flips all bits (1 becomes 0, 0 becomes 1) |
Left Shift | << |
Shifts bits left (multiplies by 2) |
Right Shift | >> |
Shifts bits right (divides by 2) |
Bitwise AND &
Returns 1
only if both bits are 1
.
x = 5 # 0b0101
y = 3 # 0b0011
result = x & y # 0b0001 (1 in decimal)
print(result) # Output: 1
Real-life Example:
- Imagine two secret agents pressing buttons to unlock a door. The door only opens if both press their buttons at the same time.
Bitwise OR |
Returns 1
if at least one bit is 1
.
x = 5 # 0b0101
y = 3 # 0b0011
result = x | y # 0b0111 (7 in decimal)
print(result) # Output: 7
Real-life Example:
- If either parent says "yes," you get ice cream!
Bitwise XOR ^
Returns 1
if only one bit is 1
(not both).
x = 5 # 0b0101
y = 3 # 0b0011
result = x ^ y # 0b0110 (6 in decimal)
print(result) # Output: 6
Real-life Example:
- A secret handshake works only when one person extends their hand, not both at the same time.
Bitwise NOT ~
Flips all bits (1 becomes 0, and 0 becomes 1). Python uses two’s complement representation, so beware of negative numbers!
x = 5 # 0b0101
result = ~x # Inverts bits and applies two's complement
print(result) # Output: -6
Real-life Example:
- Turning lights off in a room where all switches are flipped.
Left Shift <<
Moves all bits to the left, multiplying the number by 2^n
.
x = 3 # 0b0011
result = x << 2 # Shift left by 2 places (multiply by 4)
print(result) # Output: 12 (0b1100)
Real-life Example:
- Doubling the size of a pizza slice by stretching it!
Right Shift >>
Moves all bits to the right, dividing the number by 2^n
.
x = 8 # 0b1000
result = x >> 2 # Shift right by 2 places (divide by 4)
print(result) # Output: 2 (0b0010)
Real-life Example:
- Shrinking a file size by compressing it.
Summary
Operator | Symbol | Effect |
---|---|---|
AND | & |
1 if both bits are 1 |
OR | ` | ` |
XOR | ^ |
1 if only one bit is 1 |
NOT | ~ |
Flips bits (1 → 0, 0 → 1) |
Left Shift | << |
Moves bits left (multiplies by 2) |
Right Shift | >> |
Moves bits right (divides by 2) |
Now you’re a bitwise wizard! Start flipping those bits like a pro!
0 Comments