Bitwise operators are used to perform operations on values or variables, one bit at a time.
What is a Bitwise Operator?
A bitwise operator is a symbol or keyword that tells the computer what operation to perform, bit by bit, on values or variables.
The most common bitwise operators are
- & (Bitwise AND)
| - | (Bitwise OR) |
|---|
- ^ (Bitwise XOR)
- ~ (Bitwise NOT)
- << (Left shift)
- >> (Right shift)
All data in the computer is stored as sequences of 0 s and 1 s. This makes it possible to use bitwise operators to manipulate the data.
Use the simulation below to click around and see the result of different bitwise operators:
In the simulation above, the rightmost column shows the decimal values of the variables a , b , and result . The decimal numbers are displayed to give a better understanding of what happens if you do the operation 11 & 7 (using decimal numbers), and why the result is 3 .
Left shift << , and right shift >> operators shift the bits of variable a to the left or right. The number of positions to shift is specified by second variable b , that is why variable b is limited to the first 2 bits in the simulation above.
In the example below, we use the bitwise OR operator | to combine two variables stored in binary format:
Runnable example
a = 0b1010
b = 0b0110
result = a | b
print(bin(result))