Click for All Topics
Bitwise operators in Python are used to carry out operations on integers at the bit level. They manipulate the individual bits of integers and carry out several operations like AND, OR, and XOR.
Let’s take a good look at each one of them and understand the workings of all three of them separately.
The bitwise AND operator combines two integers’ corresponding bits using this operation. Only if the corresponding bits of both operands are 1, does it return a new integer with all bits set to 1. To understand this more accurately
x = 5 # binary: 0101
y = 3 # binary: 0011
result = x & y
print(result)
# Output of the above Python code:
#---> 1
As you can see in the above example, ‘x’ and ‘y’ are assigned the values ‘5’ and ‘3’. The binary representation of ‘x’ here will be ‘0101’ while for ‘y’ it’s ‘0011’.
On applying the bitwise AND operator it starts to compare the corresponding bits of both ‘x’ and ‘y’
0 1 0 1 (x)
& 0 0 1 1 (y)
-----------
0 0 0 1 (result)
Now the resulting binary value is ‘0001’ which is equivalent to decimal value 1.
This operator performs an operation on the corresponding bits of two integers. This will return a new integer where each bit of the operand is set to 1, even if one of the corresponding bits of the operand is 1. To make it much clearer, let’s look at an example:
x = 5 # binary: 0101
y = 3 # binary: 0011
result = x | y
print(result)
# Output of the above Python code:
#---> 7
Here, two integers are ‘x’ and ‘y’ with values ‘5’ and ‘3’. The binary representation of ‘x’ will be ‘0101’ and for ‘y’ it’s ‘0011’. As soon as we apply the operator, the comparison starts with the corresponding bits of both operands.
0 1 0 1 (x)
| 0 0 1 1 (y)
-----------
0 1 1 1 (result)
The binary result here is ‘0111’ which is equivalent to the decimal value 7. Hence the result is 7
Tip and Trick: Bitwise OR operations are mostly used in scenarios where you need to perform bit-level manipulations, set specific attributes, or combine different bit patterns to represent a new value.
This operator is used to flip all the bits of the binary representation of the operand, i.e., simply convert all the 0s to 1s and 1s to 0s. Here is an example to make it more clear:
x = 5 # binary: 0000 0101
result = ~x
print(result)
# Output of the above Python code:
# ---> -6
As you can see, we assigned the value ‘5’ to our variable ‘x’. The binary representation, which is ‘0000 0101’. When we apply the operator this is what we get
Original: 0000 0101
Bitwise NOT: 1111 1010
After the conversion, we have all the flipped values ‘1111 1010’, which is the decimal equivalent of -6.
Article written by Aakarsh Pandey, Team edSlash
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India