Computer >> Computer tutorials >  >> Programming >> Python

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out the bitwise operators supported by Python language with an example each in those, we use the above two variables (a and b) as operands −

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011

There are following Bitwise operators supported by Python language.

Sr.NoOperator & DescriptionExample
1& Binary AND
Operator copies a bit to the result if it exists in both operands
(a & b) (means 0000 1100)
2| Binary OR
It copies a bit if it exists in either operand.
(a | b) = 61 (means 0011 1101)
3^ Binary XOR
It copies the bit if it is set in one operand but not both.
(a ^ b) = 49 (means 0011 0001)
4~ Binary Ones Complement
It is unary and has the effect of 'flipping' bits.
(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
5<< Binary Left Shift
The left operands value is moved left by the number of bits specified by the right operand.
a << 2 = 240 (means 1111 0000)
6>> Binary Right Shift
The left operands value is moved right by the number of bits specified by the right operand.
a >> 2 = 15 (means 0000 1111)
7**= Exponent AND
Performs exponential (power) calculation on operators and assign value to the left operand
c **= a is equivalent to c = c ** a
8//= Floor Division
It performs floor division on operators and assign value to the left operand
c //= a is equivalent to c = c // a

Example

#!/usr/bin/python
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Output

When you execute the above program it produces the following result −

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15