Python Bitwise Operators – AND, OR, XOR, NOT Explained
What Are Bitwise Operators?
Bitwise operators in Python are used to perform operations on binary representations of integers. These operators manipulate individual bits, making them useful for tasks such as:
- Hardware programming
- Data compression
- Cryptography
- Flag masking and toggling
Bitwise Operators Table
| Operator | Name | Symbol | Example | Binary Result |
|---|---|---|---|---|
| AND | Bitwise AND | & | 5 & 3 | 0b0101 & 0b0011 = 0b0001 |
| OR | Bitwise OR | ` | ` | `5 |
| XOR | Bitwise XOR | ^ | 5 ^ 3 | 0b0101 ^ 0b0011 = 0b0110 |
| NOT | Bitwise NOT | ~ | ~5 | ~0b0101 = -0b0110 |
| Left Shift | Shift Left | << | 5 << 1 | 0b0101 << 1 = 0b1010 |
| Right Shift | Shift Right | >> | 5 >> 1 | 0b0101 >> 1 = 0b0010 |
Bitwise Examples in Python
AND &
a = 5 # 0b0101
b = 3 # 0b0011
print(a & b) # Output: 1 (0b0001)
OR |
print(a | b) # Output: 7 (0b0111)
XOR ^
print(a ^ b) # Output: 6 (0b0110)
NOT ~
print(~a) # Output: -6 (two's complement of 5)
Shift Left <<
print(a << 1) # Output: 10 (0b1010)
Shift Right >>
print(a >> 1) # Output: 2 (0b0010)
Binary Display with bin()
You can visualize the binary version of numbers using bin():
print(bin(5)) # '0b101'
print(bin(~5)) # '-0b110'
Use Cases
- Masking bits:
flags = 0b1010 mask = 0b0100 print(flags & mask) # Check if 3rd bit is set - Setting a bit:
flags |= 0b0001 - Clearing a bit:
flags &= ~0b0010 - Toggling a bit:
flags ^= 0b1000
Bitwise vs Logical Operators
| Type | Operator | Use Case |
|---|---|---|
| Logical | and, or | Boolean conditions |
| Bitwise | &, ` | , ^` |
Bit Length Utility
Use bit_length() to get how many bits are needed:
x = 99
print(x.bit_length()) # Output: 7
Same as len(bin(x)) - 2.
Summary Table
| Operator | Purpose | Python Example | Result (Decimal) |
|---|---|---|---|
& | Bitwise AND | 5 & 3 | 1 |
| ` | ` | Bitwise OR | `5 |
^ | Bitwise XOR | 5 ^ 3 | 6 |
~ | Bitwise NOT | ~5 | -6 |
<< | Shift left | 5 << 1 | 10 |
>> | Shift right | 5 >> 1 | 2 |
FAQs – Bitwise Operators in Python
What’s the difference between & and and in Python?
& is bitwise AND for integers. and is a logical operator for boolean expressions.
Why is ~5 equal to -6?
Because Python uses two’s complement. ~x = -(x + 1).
Can you use bitwise operators on floats?
No. Bitwise operators work only with integers.
What happens if you shift bits beyond their width?
Python integers have arbitrary precision, so shifts won’t overflow, but may lead to large numbers.
Share Now :
