Bitoperators in Python

Bitwise operators are used to process numbers with respect to their binary representation. The main task of bitwise operators is to manipulate binary values bitwise.

The operations are directly supported by the processor. Bitwise operations are required for working with device drivers, low-level graphics, cryptography, and network communication.

OperatorDescription
<<Shifts the bit pattern of the left operand to the left by the specified number of bit positions
>>Shifts the bit pattern of the left operand to the right by the specified number of bit positions
&The bit patterns of the two numbers are linked with AND
|The bit patterns of the two numbers are linked with OR
^The bit patterns of the two numbers are linked with XOR (exclusive OR)
~Results in the bitwise negation of the operand. This is also called the one’s complement.

Code Example

a, b, c = 7, 12, 15
x = a & b
# a         0111 = 7
# b         1100 = 12
# a & b     0100 = 4 --> x = 4
print("x = " + str(x))

y = a ^ c
# a         0111 = 7
# c         1111 = 15
# a ^ c     1000 = 8 --> y = 8
print("y = " + str(y))

Code Explanation

In the given code, the binary representation of the integers a, b, and c are calculated and used for bitwise operations & and ^.

The bitwise AND & operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

In this case, x = a & b:

a         0111 = 7
b         1100 = 12
a & b     0100 = 4

So, x will be equal to 4.

The bitwise XOR ^ operator compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

In this case, y = a ^ c:

a         0111 = 7
c         1111 = 15
a ^ c     1000 = 8

So, y will be equal to 8.

Output

x = 4
y = 8