Python Bitwise Operators

Python Bitwise operators help perform bit operations. First, all the decimal values will convert into binary values (bits sequence, i.e., 0100, 1100, 1000, 1001, etc.). Next, the Python bitwise operators work on these bits by shifting left to right or transforming bit values from 0 to 1 and vice versa.

The below table shows the different Python Bitwise operators and their meanings. For example, Consider x = 6 and y = 8 and their values in binary form are: x = 0110 and y = 1000

OperatorsMeaningExamples
&Bitwise ANDX & Y = 0000
|ORX | Y = 1110
^exclusive ORX ^ Y = 1110
~complement~X = 00001001 (Not operator will convert all 0 into 1.)
<<Shift leftX << 1 = 00001100 (Bits will move 1 step left. If we use 2 or 3, then they shift accordingly)
>>Shift rightY >> 1 = 00000100

The Truth Table behind Python Bitwise Operators is:

xyx & y X | yx ^ y
00000
01011
10011
11110

Python Bitwise Operators Example

In this example, we use two variables, a and b, whose values are 9 and 65. Next, we use them to show you the list of Bitwise operations.

a = 9
b = 65
print("AND On 9 and 65 is = ", a & b)
print("OR On 9 and 65 is = ", a | b)
print("EXCLUSIVE OR On 9 and 65 is = ", a ^ b)
print("NOT On 9 is = ", ~a)

print("LEFT SHIFT On 9 is = ", a << 1)
print("RIGHT SHIFT On 65 is = ", b >> 1)
Python Bitwise Operators 1

In this Python bitwise operators program, we declared two integers, a and b, and assigned the values 9 and 65. The binary form of 9 = 00001001 and 65 = 01000001.

>>> a = 9
>>> b = 65

Let’s see the Python calculations of these Operators
AND Operation = a&b
00001001 & 01000001 = 00000001 = 1

OR Operation on integer values = a | b
00001001 | 01000001 = 01001001 = 73

The Exclusive OR Operation = a^b
00001001 ^ 01000001 = 01001000 = 72

Right Shift Operation = b >> 1
01000001 >> 1 = 00100000 = 32

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.

Comments are closed.