Bitwise Operators in Python

FREE Online Courses: Your Passport to Excellence - Start Now

You would have heard of operators like addition, subtraction, etc. Wondering what these “Bitwise Operators” are?

These are also symbols performing modifications on numbers, but at a low level called the Binary system. All the operations done on computers are transformed to this system to make the computers understand. Want to explore more about it? Let’s not wait and begin.

Overview on Binary System and Bits

Before talking about the binary operators, first, let’s discuss the binary system and bits. We are familiar with the decimal system where we have a base as 10, i.e., every digit is multiplied with the 10 to the power of the digit’s place.

Bitwise Operators in Python

Similarly, the binary system has a base as 2 and thus has only 0s and 1s. The below picture gives an example of a binary number and its decimal value.

Bitwise Operator in Python

In Python, the binary equivalents are shown using the bin() function. The binary numbers in Python start with ‘0b’ with the actual number as a continuation.

Example of finding binary number using bin():

bin(6)

Output:

‘0b110’

Bit (Binary digit) represents each digit of a binary number. In the above example, the binary number of 6 has 1,1, and 0 are bits. Here we got these bits because
1*(22) + 1*(21)+0*(20)
=4+2+0
=6
Example of finding binary number using bin():

bin(25)

Output:

‘0b11001’

In this example, the bits are 1, 1, 0, 0, and 1. These represent 25 in the following way,
1*(24) + 1*(23)+0*(22)+0*(21) + 1*(20)
=16+8+0+0+1
=25

Bitwise Operators in Python

Bitwise operators perform operations on the bits, rather than on the number as a whole. And they give the new number as the result. In Python, these operators work on integers. We have the following binary operators:

1. Logical Operators

  • AND (&) operator
  • OR (|) operator
  • NOT(~) operator
  • XOR (^) operator

2. Shift Operators

  • Left shift (<<) operator
  • Right shift (>>) operator

We will discuss these operators one by one in the following sections.

Binary Logical Operators in Python

1. Bitwise AND Operator (&) in Python

If we have two statements joined by ‘and’, then it means that both statements have to be ‘True’ for the whole logic to be true. Similarly, if the corresponding bits are 1 only then the logic will be 1 using an operator. See the below example and table.

Bitwise AND Operator

Example of AND Operation in Python:

5&7

Output:

5

In the above example,
5 = 0101 and 7=0111
5&7 = 0 1 0 1 &
0 1 1 1
=0 1 0 1
=5
Example of AND Operation in Python:

10&4

Output:

0

In the above example,
10 = 1010 and 4=0100
10&4 = 1 0 1 0 &
0 1 0 0
=0 0 0 0
=0

2. Bitwise OR Operator (|) in Python

When two statements are joined by or, then the overall logic will be true if any of the two is true. The work of the bitwise OR is also the same. It gives output as 1 when either of the bits is 1. For a further understanding look at the below images.

Bitwise OR Operator in Python

Example of OR operator in Python:

5 | 7

Output:

7

In the above example,
5 = 0101 and 7=0111
5&7 = 0 1 0 1 |
0 1 1 1
=0 1 1 1
=7
Example of OR operator in Python:

10|4

Output:

14

In the above example,
10 = 1010 and 4=0100
10&4 = 1 0 1 0 |
0 1 0 0
=1 1 1 0
=14

3. Python Bitwise NOT Operator (~):

This operator works on a single number and inverts all the bits. Then gives the output as the resultant new number. This works like a negation of a statement. Refer to the below pictures for understanding more.

Bitwise NOT Operator in Python

It is also called one’s complement. Because it inverts the bits. It is important to observe that the NOT of a number n gives -n-1 as the result.

Example of NOT Operation in Python:

~4

Output:

-5

In the above example,
4 = 0100 (Here the right digit represents a sign. 1 means negative and 0 means positive)
~4= ~ 0 1 0 0
= -(0 1 0 0 +1)
=- (0 1 0 1)=-5
We can see that binary forms of 4 and 5, 0100 and 1011 respectively, have each bit complementing. That is, if one number has 1 as its bit at a particular position then the other one has 0. So, this operator is called 1’s complement.

Example of NOT Operation in Python:

~-10

Output:

9

In the above example,
-10 = 11010 (Here the right digit represents a sign. 1 means negative and 0 means positive)
~-10 = ~1 1 0 1 0
= -( 1 1 0 1 0 +1 )
=-(1 1 0 1 0)-1
= 10-1 =9

4. Python Bitwise XOR Operation (^):

This operation might be new for you guys. This operates on two numbers. It gives 1 when the bits are different and gives 0 when both the bits are either 0 or 1. See the following images for getting the concept clear.

Bitwise XOR Operator in Python

Example of XOR operation in Python:

8^4

Output:

12

In the above example,
8 = 1000 and 4=0100
8^4 = 1 0 0 0 ^
0 1 0 0
=1 1 0 0
=12
Example of XOR operation in Python:

10^3

Output:

9

In the above example,
10 = 1010 and 3=0011
10^3 = 1 0 1 0 ^
0 0 1 1
=1 0 0 1
=9

Shift Operators in Python

1. Python Bitwise Left Operator (<<):

This operator shifts the bits of a number to the right and fills the voids at the right end by 0. The shifting is done by the number of places specified.

Shifting the digits by one place to the left results in the doubling of the number. Similarly, increasing the number of shifts results in a higher power of double

Bitwise Left Shift Operator in Python

Example of the left shift in Python:

5<<1

Output:

10

In the above example,
5 = 0101
5<<1 = 0 1 0 1 _
=0 1 0 1 0
=10
Example of the left shift in Python:

8<<3

Output:

64

In the above example,
8 = 1000
8<<3 = 1 0 0 0 _ _ _
= 1 0 0 0 0 0 0
=64

2. Python Bitwise Right Operator (>>):

It shifts the bits of a number to the right by the specified number of places. And also fills the voids at the left end with zeros.

This operation halves the numbers on shifting by one place. If shifter by more than 1 place, results in the quotient obtained by dividing the number with two to the power of places

Bitwise Right Shift Operator in Python

Example of the right shift in Python:

34>>1

Output:

17

In the above example,
34 = 100010
34>>1 = _100010
=0 1 0 0 0 1 0
=0 1 0 0 0 1
=17
Example of the right shift in Python:

25>>3

Output:

3

In the above example,
25 = 11001
25>>3 = _ _ _1 1 0 0 1
=0 0 0 1 1 0 0 1
=0 0 0 1 1 =3

Bitwise Operators Overloading in Python

Overloading is a method of giving extra functionality to an operator, other than its predefined one. A simple example of overloading is using the ‘+’ operator on integers and strings. When we use it with integers it adds numbers in the same way as we do mathematics. But if we use the same operator on strings, which are of different data type/class, it behaves in a different way by concatenating them. The ‘+’ operator is said to be overloaded.

We can overload all the existing operators in Python. We can do this by using a magic function, starting and ending with double underscores, that invokes whenever the associated operator is used. This function should have the required operations that we want the operator to do. An example of overloading bitwise operators is shown below.

Example of overloading bitwise Operators:

class BitwiseOverload(): #creating a class
  def __init__(self,val): #defining init function
    self.val=val
  def __or__(self,obj): #overloading OR operator
    print("Overloading OR operator")
    if isinstance(obj,BitwiseOverload): #checking if the object is defined in the class
      return self.val | obj.val #doing OR operation on values of both the objects
    else:
      raise ValueError #if not defined in the class showing an error
  def __and__(self,obj): #overloading AND operator
    print("Overloading AND operator")
    if isinstance(obj,BitwiseOverload): #checking if the object is defined in the class
      return self.val & obj.val #doing AND operation on values of both the objects
    else:
      raise ValueError #if not defined in the class showing an error
  def __xor__(self,obj): #overloading XOR operator
    print("Overloading XOR operator")
    if isinstance(obj,BitwiseOverload): #checking if the object is defined in the class
      return self.val ^ obj.val #doing XOR operation on values of both the objects
    else:
      raise ValueError #if not defined in the class showing an error
  def __invert__(self):#overloading NOT operator
    print("Overloading NOT operator")
    return ~self.val #doing NOT operation on value of the object
  def __lshift__ (self,obj): #overloading LeftShift operator
    print("Overloading LeftShift operator")
    if isinstance(obj,BitwiseOverload): #checking if the object is defined in the class
      return self.val << obj.val #doing LeftShift operation on value by the value of the object
    else:
      raise ValueError #if not defined in the class showing an error
  def __rshift__ (self,obj): #overloading RightShift operator
    print("Overloading RightShift operator")
    if isinstance(obj,BitwiseOverload): #checking if the object is defined in the class
      return self.val >> obj.val #doing RightShift operation on value by the value of the object
    else:
      raise ValueError #if not defined in the class showing an error
if __name__=='__main__':
  obj=BitwiseOverload(4)
  obj2=BitwiseOverload(10)
  print("obj1&obj2:",obj&obj2)
  print("obj1|obj2:",obj|obj2)
  print("obj1^obj2:",obj^obj2)
  print("obj2>>obj1:",obj2>>obj)
  print("obj2<<obj1:",obj2<<obj)
  print("~obj1:",~obj)

Output:

Overloading AND operator
obj1&obj2: 0
Overloading OR operator
obj1|obj2: 14
Overloading XOR operator
obj1^obj2: 14
Overloading RightShift operator
obj2>>obj1: 0
Overloading LeftShift operator
obj2<<obj1: 160
Overloading NOT operator
~obj1: -5

Interview Questions on Python Bitwise Operator

Question time! Let’s look at some interview questions under Bitwise Operators.

Q1. Find quotient on dividing a number by ith power of 2.

Ans 1. The right shift operator gives the quotient on dividing a number by a power of 2. If we want to divide by 2 to the power of ‘i’, then we can shift then we have to shift by ‘i’ places.

Example of using right shift to find the quotient on dividing a number by ith power:

45>> 3

30>>2

Output:

5
7

Q2. Write code to check if the number is even or not without using the % operator.

Ans 2. When a number is even, the leftmost bit will be zero and if it’s odd its leftmost bit will be one. Using this logic, if we do AND of the number with 1 whose leftmost digit is 1 and rest are 0s. We get 1 if the number is odd and 0 if even.

Example of finding if a number is even using AND operator:

25&1

4&1

Output:

1
0

Q3. Check if the ith index is 1 or not using bitwise operation.

Ans 3. We want to check if the ith index is 1 or not. Then we can shift 1 to the left by ‘i’ places. Then do AND operation with 1 and the number. This will give zero if the bit at ith index is not 1 and gives a non-zero number if it is 1.

Example of checking if the ith index is 1 or 0 using left shift operator:

bin(7)
#checking if 3rd bit is 1 or not
a=1<<2
7&a

Output:

‘0b111’
4

Example of checking if the ith index is 1 or 0 using left shift operator:

bin(10)
#checking if 3rd bit from left is 1 or not
a=1<<2
10&a

Output:

‘0b1010’
0

Q4. Check if two numbers have the same sign or not using bitwise operators.

Ans 4. The sign on a number depends on the leftmost digit. If the leftmost digits have the same sign then the XOR operator will result in 0 at that digit, which will result in a positive number. If they have opposite signs, one will have 1 as the right digit and the other 0. This will give 1 on XOR and the result will be negative.

Example of checking if two numbers are of same sign using XOR operator:

-10^4

Output:

-14

Example of checking if two numbers are of same sign using XOR operator:

-10^-4

Output:

10

Q5. Swap two numbers without using a third variable.

Ans 5. Swapping can be done using the XOR operator. A third dummy variable is not required in this case. Swapping can be done in the following way:

Example of swapping two numbers using XOR operation:

a=10
b=5
a=a^b
b=a^b
a=a^b
print("a=",a,"b=",b)

Output:

a= 5 b= 10

Quiz on Bitwise Operator in Python

Conclusion

In this article, we learned about bits and different bitwise operators. We also saw their functioning and Python code. Then we saw some interview questions on Bitwise Operators.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

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