Python Program to Add Two Numbers using Bitwise Operators

In this article, we will learn about python program to add two numbers using bitwise operators.

Getting Started

In python, we can add two numbers using addition operator. However, we can also use bitwise operators to get sum of two numbers.

It can be done as shown below –

 
def addWithBitwiseOperator(x, y):

    while (y != 0):
         
        # Calculates carry using bitwise AND operator
        carry = x & y
         
        ## Calculates sum using bitwise XOR operator
        x = x ^ y
 
        # Shifts the carry to left by 1 bit.
        y = carry << 1
    return x
 
 
print("Sum =", addWithBitwiseOperator(150, 31))

Output:

 
Sum = 181

In above program,

  • x & y calculates carry using bitwise AND operator.
  • x ^ y calculates sum using bitwise XOR operator.
  • carry << 1 shifts carry to left by 1 bit.

Here, we have used Half Adder Logic.

Using Bitwise Operator and Recursion to Add Two Numbers

We can also use recursion and bitwise operators to add two numbers in python. It can be done as shown below –

 
def addWithBitwiseOperator(x, y):
    if (y == 0):
        return x
    else:
        return addWithBitwiseOperator( x ^ y, (x & y) << 1)
         
print("Sum =", addWithBitwiseOperator(15, 31)) 

Output:

 
Sum = 46

In above code,

  • In each recursive function call, x contains sum and y contains carry shifted to left by 1 bit.
  • Recursive call terminates when value of y becomes 0 i.e. carry becomes 0.
  • x ^ y returns sum of set bits of x and y.
  • x & y returns carry bits between x and y.
  • (x & y) << 1 returns carry bit shifted to left by 1 bit.

That’s how we can write python program to add two numbers using bitwise operators

Learn more python examples at – https://tutorialwing.com/python-tutorial/

Leave a Reply