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.
Operator | Symbol | Example | Description |
AND | & | x & y | Returns the result of bitwise AND operation between x and y. |
OR | | | x | y | Returns the result of bitwise OR operation between x and y. |
NOT | ~ | ~x | Returns the bitwise NOT of x. The result is one’s complement of x. |
XOR | ^ | x ^ y | Returns the result of bitwise XOR operation between x and y. |
Left Shift | << | x << y | Left shifts the bits of x by y positions, and returns the result. Fills zeros on the right side during shift. |
Right Shift | >> | x >> y | Right 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 Code CopyOutput
x & y : 4
x | y : 13
~x : -13
x ^ y : 9
x << y : 384
x >> y : 0
Bitwise Operators 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.