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’s 1s to 0s and 0s to 1s.
<<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 inverts the bits of the number, i.e. replaces 1’s with 0’s and 0’s with 1’s.

Bitwise or operator inverts the number as per the 2’s compliment. Bitwise NOT of number x results in -(x + 1).

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

Resources

Handwritten Notes

References

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