Python Bitwise Operators

Bitwise Operators

Bitwise Operators are used to perform gate operations like AND, OR, NOT, XOR, etc., at bit level data.

The following tables presents all the Bitwise Operators available in Python, with respective operator symbol, description, and example.

OperatorSymbolExampleDescription
AND&x & yReturns the result of bitwise AND operation between x and y.
OR|x | yReturns the result of bitwise OR operation between x and y.
NOT~~xReturns the bitwise NOT of x. The result is one’s complement of x.
XOR^x ^ yReturns the result of bitwise XOR operation between x and y.
Left Shift<<x << yLeft shifts the bits of x by y positions, and returns the result. Fills zeros on the right side during shift.
Right Shift>>x >> yRight shifts the bits of x by y positions, and returns the result. Fills zeros on the left side during shift.

Examples

In the following program, we take numeric values in x, y; and perform bitwise operations.

Python Program

x = 12
y = 5

print(f'x & y  : {x & y}')
print(f'x | y  : {x | y}')
print(f'~x     : {~x}')
print(f'x ^ y  : {x ^ y}')
print(f'x << y : {x << y}')
print(f'x >> y : {x >> y}')
Run

Output

x & y  : 4
x | y  : 13
~x     : -13
x ^ y  : 9
x << y : 384
x >> y : 0

Tutorials

The following tutorials provide syntax, usage, and examples, for each of the Bitwise Operators in detail.

Summary

In this tutorial of Python Examples, we learned about Bitwise Operators, and how to use them in programs for bit level operations: AND, OR, NOT, XOR, Left Shift, and Right Shift.