Python Bitwise Operators

Operators are used to performing operations on values and variables. These symbols carry out all kinds of computations. The value on which the operator operates on is known as Operand.

In Python, bit-wise operators are used to performing calculations on integers according to the bits. The integers are converted into binary and then bit by bit operations are performed. Then, the result is stored back in decimal format.


Types of Bitwise Operators in Python

OPERATORSYNTAX
Bitwise AND (&)x & y
Bitwise OR (|)x | y
Bitwise NOT (~)~x
Bitwise XOR (^)x ^ y
Bitwise right shift (>>)x>>
Bitwise left shift(<<)x<<

1. Bitwise AND Operator

The statement returns 1 when both the bits turn out to be 1 else it returns 0.

x = 5 = 0101 (Binary)

y = 4 = 0100 (Binary)

x & y = 0101 & 0100 = 0100 = 4 (Decimal)


2. Bitwise OR Operator

The statements return 1 when either of the bits turns out to be 1 else it returns 0.

x = 5 = 0101

y = 4 = 0100

x & y = 0101 | 0100 = 0101 = 5 (Decimal)


3. Bitwise NOT Operator

The statement returns one’s complement of the number mentioned.

x = 5 = 0101

~x = ~0101

= -(0101 + 1)

= -(0110) = -6 (Decimal)


4. Bitwise XOR Operator

The statement returns true if any one of the bit is 1 and the other bit is 0, otherwise it returns false.

x = 5 = 0101 (Binary)

y = 4 = 0100 (Binary)

x & y = 0101 ^ 0100

= 0001

= 1(Decimal)


Bitwise Shift Operators

Shift operators are used to shifting the bits of a number left or right thereby multiplying or dividing the number by two respectively. They are used when we have to multiply or divide a number by two.

5. Bitwise Right Shift Operator

It shifts the bits of the number to the right and fills 0 on blank/voids right as a result. It provides a similar kind of effect as of dividing the number with some power of two.

x = 7

x >> 1

= 3


6. Bitwise Left Shift Operator

It shifts the bits of the number to the left and fills 0 on blank/voids left as a result. It provides a similar kind of effect as of multiplying the number with some power of two.

x = 7

x << 1

= 14


Python Bitwise Operators Example

a = 5
b = 6
    
# Print bitwise AND operation    
print("a & b =", a & b)  
    
# Print bitwise OR operation  
print("a | b =", a | b)  
    
# Print bitwise NOT operation   
print("~a =", ~a)  
    
# print bitwise XOR operation   
print("a ^ b =", a ^ b)  
   

c = 10
d = -10
  
# print bitwise right shift operator 
print("c >> 1 =", c >> 1) 
print("d >> 1 =", d >> 1) 
  
c = 5
d = -10
  
# print bitwise left shift operator 
print("c << 1 =", c << 1) 
print("d << 1 =", d << 1) 

Output:

a & b = 4
a | b = 7
~a = -6
a ^ b = 3
c >> 1 = 5
d >> 1 = -5
c << 1 = 10
d << 1 = -20

References