Python Bitwise Operators


Introduction to Python Bitwise Operators

Python Bitwise Operators are used to perform bit by bit operations. It will convert the number into the binary form and then perform the specified operation. These operators do not return True or False, instead perform bitwise calculations.

OperatorNameDescription
&Bitwise ANDReturns binary 1 if both bits are 1, else 0.
|Bitwise ORReturns binary 1 if any of the bit is 1, else 0.
^Bitwise XORReturn binary 1 if only 1 bit is 1.
~Bitwise NOTConvert 1s to 0s and 0s to 1’s, i.e. inverts the bits.
<<Bitwise left shiftShifts bits left and fills new bits with 0.
>>Bitwise right shiftShifts bits right and fills new bits with 0.

Python Bitwise Operators

Bitwise AND Operator

It returns binary 1 if all the bits are 1, and if any of the bits is 0, then it returns 0.

Illustration:

Numeric ValueBinary Value
2010
3011
Bitwise AND2010

Example:

In [1]:
print(2 & 3)
2

Bitwise OR Operator

It returns binary 1 if any of the bits is 1, and if all the bits are 0, then it returns 0.

Illustration:

Numeric ValueBinary Value
2010
3011
Bitwise OR3011

Example:

In [1]:
print(2 | 3)
3

Bitwise XOR Operator

It returns 1 only if one of the bits is 1, i.e. one bit is 1 and the second is 0. It returns 0 if both the bits are same, either 1 or 0.

The Caret sign (^) is used for Bitwise XOR.

Illustration:

Numeric ValueBinary Value
2010
3011
Bitwise XOR1001

Example:

In [1]:
print(2 ^ 3)
1

Bitwise NOT Operator

It actually returns one’s complement of the number. But because one’s complement inverts the sign bit, we get the Negative number and a negative number is saved as the two’s complement in the memory, so the result is again converted into two’s complement. The result is equivalent to -(x+1).

Let’s Understand with an example below:

Bitwise NOT Operator

The Tilde sign (~) is used for Bitwise NOT.

Illustration:

Numeric ValueBitwise NOT
3-4
-43

Example:

In [1]:
print(~3)
-4
In [2]:
print(~-4)
3

Bitwise left shift Operator

It moves the bits left by the specified number of positions.

Illustration:

Numeric InputBitwise ValueLeft shift by 1Numeric Output
2001001004
4010010008

Example:

In [1]:
print(2 << 1)
4
In [2]:
print(4 << 1)
8

Bitwise right shift Operator

It moves the bits right by the specified number of positions.

Illustration:

Numeric InputBinary ValueRight shift by 1Numeric Output
2001000011
4010000102

Example:

In [1]:
print(2 >> 1)
1
In [2]:
print(4 >> 1)
2

References

  1. Bitwise Operators in Python
  2. Bitwise Operators
  3. Bitwise Left Shift Operator and Right Shift