Python Bitwise Operators

Bitwise Operators in Python

In this tutorial, you will be learning about the Bitwise operators in python. In computer all the data is stored in the form of bits.

Bitwise operators always works on the binary numbers.

Operators                                        Example                                   Meaning


&                                                             a & b                                              Bitwise AND


|                                                              a | b                                                Bitwise OR


^                                                            a ^ b                                               Bitwise XOR


~                                                         ~a                                                      Bitwise NOT


<<                                                            a << b                                              Bitwise left shift


              >>                                                               a >> b                                             Bitwise right shift

Bitwise AND operator

It takes two equal length bits as parameters and performs AND operation, which means it returns 1 if both the bits in the compared position are 1 else returns 0.

Bitwise OR operator

It takes two equal length bits as parameters and performs OR operation, which means it returns 0 if both the bits in the compared position are 0 else returns 1.

Bitwise XOR operator

This operator is also known as exclusive OR .
It performs exclusive OR operation between two bits, which means it returns 1 if the bits are different else returns 0.

Bitwise NOT operator

It only operates with one operator and does not require two operators like others. It returns the one’s complement of a number, which means it alters the bits by converting 1 to  0 and o to 1.

Bitwise left shift operator

Shifts the bits to the left and replaces the void places on the right with 0.

Bitwise right shift operator

Shifts the bits to the right and replaces the void places on the left with 0.

Example

The below example gives you the better idea of bitwise operators.

a = 60
b = 13
print("a & b =", a & b)
print("a | b =", a | b)
print("a ^ b = ", a ^ b)
print(" ~a =", ~ a)
print(" a<<b =", a << b)
print("a >> b =", a>>b)

  The above code gives the output of all the bitwise operations performed on the values 60 & 13

Output:

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top