In this tutorial you will learn about the Bitwise operators in Python. In python bitwise operators are used to perform bitwise calculations on integers. These integers are first converted into binary and then operations are performed on each bit.
Python provides several bitwise operators each serving a unique purpose. These operators include
- AND
- OR
- NOT
- XOR
- Shift operations
Bitwise AND:
The bitwise AND operator (&) performs logical conjunction on the corresponding bits of its operands. If both operand bits are 1 then result bit is 1 otherwise result bit is 0.
1 0 0 1 1 1 0 0
AND(&)
0 0 1 1 0 1 0 0
0 0 0 1 0 1 0 0 -> The Resulting bit pattern
For example:
a = 12 b = 13 print("a & b =", a & b)
Output:
a & b = 12
Bitwise OR:
The bitwise OR operator performs logical disjunction. If one of the operand bit is 1 then result bit is 1 otherwise result bit is 0.
1 0 0 1 1 1 0 0
OR(|)
0 0 1 1 0 1 0 0
1 0 1 1 1 1 0 0 ->The Resulting bit pattern
For example:
a = 12 b = 13 print("a | b =",a | b)
Output:
a | b = 13
Bitwise XOR:
The bitwise XOR operator is also known as exclusive or operator, is used to perform xor operation on two operands. It compares corresponding bits of two operands. If the bits are different, it returns 1, otherwise, it returns 0.
1 0 0 1 1 1 0 0
XOR(^)
0 0 1 1 0 1 0 0
1 0 1 0 1 0 0 0 -> The Resulting bit pattern
For Example:
a = 25 b = 30 print("a ^ b =", a ^ b)
Output:
a ^ b = 7
Bitwise NOT:
The python Bitwise NOT (~) operator works with a single value and returns its one’s complement. It performs logical negation on a given number by flipping all of its bits.
1 1 0 0 1 0 1 1
NOT (~)
0 0 1 1 0 1 0 0 -> The Resulting bit pattern
For example:
a = 10 print("~a =", ~a)
Output:
~a = -11
Bitwise shift operators:
Bitwise shift operators are used to shift the bits of a number to the left or right. There are two primary types of bitwise operations: the left shift operator (<<) and the right shift operator (>>).
Left shift Operator :
The left shift operator shifts the bits of a number to the left by the specified number of positions. This is equivalent to multiplying the number by 2 to the power of the number of positions shifted. for example, 10 << 2 is equal to 40, because 10 in binary is 1010 and shifting it to the left by 2 positions gives us 101000, which is equal to 40 in decimal.
for example:
a = 10 print("a << 2 =", a << 2)
Output:
a << 2 = 40
Right shift Operator:
The right shift operator shifts the bits of a number to the right by the specified number of positions. This is equivalent to dividing the number by 2 to the power of the number of positions shifted. For example, 10 >> 2 is equal to 2, because 10 in binary is 1010 and shifting to the right by 2 positions gives us 10, which is equivalent to 2 in decimal.
For example:
a = 10 print("a >> 3 =", a >> 3)
Output:
a >> 3 = 1