Bitwise Operators
4 min read ·
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:
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.
Explanation:
0101
0011
----
0001 -> 1
Bitwise OR (|)
Sets a bit if any one bit is 1.
Explanation:
0101
0011
----
0111 -> 7
Bitwise XOR (^)
Sets a bit if bits are different.
Explanation:
0101
0011
----
0110 -> 6
Bitwise NOT (~)
Inverts all bits.
Explanation:
~0101 = -(5 + 1) = -6
Bitwise Left Shift (<<)
Shifts bits to the left (multiplies by powers of 2).
Explanation:
5 << 1 = 10
5 << 2 = 20
Bitwise Right Shift (>>)
Shifts bits to the right (divides by powers of 2).
Explanation:
20 >> 1 = 10
20 >> 2 = 5
Bitwise Operators with Assignment
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 |
Common Use Case: Flags
Common Mistakes
Confusing Logical and Bitwise Operators
Correct:
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