Bitwise operators are used to perform operations on binary (bit-level) representations of integers. These operators work directly on the bits (0s and 1s) of numbers.
They are mainly used in:
Before understanding bitwise operators, consider:
5 → 0101
3 → 0011
(All operations are performed bit by bit)
| Operator | Name | Description | |
|---|---|---|---|
& |
AND | Sets bit to 1 if both bits are 1 | |
| ` | ` | OR | Sets bit to 1 if at least one bit is 1 |
^ |
XOR | Sets bit to 1 if bits are different | |
~ |
NOT | Inverts all bits | |
<< |
Left Shift | Shifts bits to the left | |
>> |
Right Shift | Shifts bits to the right |
&)a = 5 # 0101
b = 3 # 0011
print(a & b)
Output
1
Explanation
0101
& 0011
------
0001 → 1
|)print(5 | 3)
Output
7
Explanation
0101
| 0011
------
0111 → 7
^)print(5 ^ 3)
Output
6
Explanation
0101
^ 0011
------
0110 → 6
~)print(~5)
Output
-6
Explanation
~n = -(n + 1)~5 = -6<<)Shifts bits to the left.
print(5 << 1)
Output
10
Explanation
5 → 0101
Shift left → 1010 → 10
👉 Equivalent to multiplying by 2
>>)Shifts bits to the right.
print(5 >> 1)
Output
2
Explanation
5 → 0101
Shift right → 0010 → 2
👉 Equivalent to dividing by 2
a = 6 # 0110
b = 2 # 0010
print("AND:", a & b)
print("OR:", a | b)
print("XOR:", a ^ b)
print("Left Shift:", a << 1)
print("Right Shift:", a >> 1)
Works only with integers
Operates on binary values
~ uses 2’s complement representation
Shifting:
<< multiplies by 2>> divides by 2Bitwise operators work at the bit level.
Types include:
& (AND)| (OR)^ (XOR)~ (NOT)<< (Left Shift)>> (Right Shift)Used in low-level operations and optimizations.
Understanding binary representation is essential.