βοΈ Python Bitwise Operators β Working at the Binary Level
Introduction π
Bitwise operators allow you to work with numbers at the **binary level**. They are extremely useful in low-level programming, optimization, encryption, networking, and performance-critical tasks.
Note
π‘ Bitwise operations work on the binary representation of integers (0s and 1s).
1. List of Bitwise Operators π
| Operator | Symbol | Description | Example |
|---|---|---|---|
| AND | & | Sets bit to 1 if both bits are 1 | 5 & 3 |
| OR | | | Sets bit to 1 if any bit is 1 | 5 | 3 |
| XOR | ^ | Sets bit to 1 if bits are different | 5 ^ 3 |
| NOT | ~ | Flips all bits | ~5 |
| Left Shift | << | Shifts bits left, filling with 0s | 5 << 1 |
| Right Shift | >> | Shifts bits right | 5 >> 1 |
2. Understanding Binary Representation π’
binary.py
print(bin(5)) # 0b101
print(bin(3)) # 0b0115 = 101 (binary)3 = 011 (binary)
3. Bitwise AND (&) π©
Returns 1 only if both bits are 1.
and_op.py
print(5 & 3) # 1
print(bin(5 & 3)) # 0b1Note
Explanation: 101 & 011 β 001 (binary) β 1
4. Bitwise OR (|) π¦
Returns 1 if any bit is 1.
or_op.py
print(5 | 3) # 7
print(bin(5 | 3)) # 0b111Note
Explanation: 101 | 011 β 111 (binary) β 7
5. Bitwise XOR (^) π¨
Returns 1 only if bits are different.
xor_op.py
print(5 ^ 3) # 6
print(bin(5 ^ 3)) # 0b110Note
Explanation: 101 ^ 011 β 110 (binary) β 6
6. Bitwise NOT (~) π
Flips all bits β also known as 1βs complement.
not_op.py
print(~5) # -6Note
π§ Formula: ~x = -(x + 1)Example: ~5 = -(5 + 1) = -6
7. Left Shift (<<) β¬ οΈ
Shifts bits to the left β adds zeros at the end.
left_shift.py
print(5 << 1) # 10
print(bin(5 << 1)) # 0b1010Note
Shifts 101 β 1010 (binary)
8. Right Shift (>>) β‘οΈ
Shifts bits to the right β drops rightmost bit.
right_shift.py
print(5 >> 1) # 2
print(bin(5 >> 1)) # 0b10Note
Shifts 101 β 10 (binary)
9. Bitwise Operators With Variables π―
variables_bitwise.py
x = 12 # 1100
y = 10 # 1010
print(x & y) # 1000 -> 8
print(x | y) # 1110 -> 14
print(x ^ y) # 0110 -> 610. Useful Real-World Examples π
Check If a Number Is Even or Odd
even_odd.py
num = int(input("Enter a number: "))
if num & 1 == 0:
print("Even")
else:
print("Odd")Swapping Two Numbers Without Temporary Variable
swap.py
a = 5
b = 3
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b)Bit Masking Example
bitmask.py
permissions = 0b1010 # read + write
mask = 0b0010 # check write permission
if permissions & mask:
print("Write allowed")
else:
print("Write denied")Conclusion π
>>βBitwise operators unlock Pythonβs low-level power β perfect for optimization and binary operations.β β‘
You now understand all bitwise operators with examples and real-world use cases. Want the next topic? Try Conditional Statements, Loops, Expressions, or Control Flow. Just tell me! π