7️⃣ Bitwise Operators
Bitwise operator perfoms logical operations on binary numbers. Binary numbers are represented using only two digits (0 or 1). So those digits (0, 1) are also called as bits. So the operators which performs operations on bits are bitwise operators Lets define two binary numbers a = 10 (1010), b = 8 (1000) and perform binary operations on them. We can also use bin method on them to view their binary representation.
💻 Example:
1 2 3 4 | a = 10
b = 8
print(bin(a))
print(bin(b))
|
✅ Output:
'0b1010'
'0b1000'
1) Bitwise and (&):
It perfoms logical and on corresponding bits of both variables.
💻 Example:
1 | print(a & b)
|
✅ Output:
8
2) Bitwise or (|):
It perfoms logical or on corresponding bits of both variables.
💻 Example:
1 | print(a | b)
|
✅ Output:
10
3) Bitwise xor (^):
It perfoms logical xor on corresponding bits of both variables.
💻 Example:
1 | print(a ^ b)
|
✅ Output:
2
4) Bitwise 1’s complement (~):
It returns bitwise negation of a value where each bit of a variable is inverted.
💻 Example:
1 2 | print(~a)
print(~b)
|
✅ Output:
-11
-9
5) Bitwise left shift (<<):
It shifts bits of a variable to left side for a value by a given number of places and adds zeros (0’s) to new positions. Lets shift bits of variable a and b to left by 2 positions.
💻 Example:
1 2 | print(a << 2)
print(b << 2)
|
✅ Output:
40
32
6) Bitwise right shift (>>):
It shifts bits of a variable to right side for a value by a given number of places and adds zeros (0’s) to new positions. Bits are lost in this process. Lets shift bits of variable a and b to right by 2 positions.
💻 Example:
1 2 | print(a >> 2)
print(b >> 2)
|
✅ Output:
2
2
Here are the quick notes on above topic:
Follow below video to clear the concepts practically. Bitwise operators are explained in details.
Be prepared with below questions prior to your interview !
Frequently asked Interview Questions
What are bitwise operators in Python?
What is the result of the expression (5 & 3)?
How do bitwise left shift (<<) and right shift (>>) operators work in Python?