Bitoperators

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.

Example

Code Explanation

LineDescription
1Initializes the variables
a with value 7,
b with value 12 and
c with value 15
2Calculates the and concatenation of the bit patterns of a and b
6Outputs the and concatenation of the bit patterns of a and b represented as string
8Calculates the XOR concatenation of the bit patterns of a and b
12Outputs the XOR concatenation of the bit patterns of a and b represented as string
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))
Output
x = 4
y = 8