Bitwise recursive addition of two integers in C

CServer Side ProgrammingProgramming

In this problem, we are given two numbers. Our task is to create a C program for the Bitwise recursive addition of two integers.

The logic to find the sum using the Bitwise operations is similar to what we used to do when we were in preschool. For finding the sum, we used to add each digit of the number and if a carry is there, we add it to the next digit.

We will do a similar thing, find the sum using the XOR operator and check for the carry using the AND operation. If there is a carry we will add it back to the number otherwise not.

This is the logic of a Half-Adder which you might have learned in digital Electronics. Refer here…

Now, The sum is calculated using a^b i.e. an XOR b and we need to check for an extra carry that needs to be propagated if the first bit of both is set or so. And we need to add an extra set bit to the number.

So, a bit algorithm will be

Step 1 − Find XOR of a and b i.e. a^b and store it in the result variable.

Step 2 − Check if {(a & b) << 1} == 0

Step 2.1 − If it is equal to 0, then print the result, it is the final result.

Step 2.2 − If it is not equal to 0, then go to step 1, with a = {(a & b) << 1} and b = result.

Example

Program to illustrate the working of the algorithm −

 Live Demo

#include <stdio.h>
int addNumbers(int a, int b) {
   int carry = (a & b) << 1;
   int result = a^b;
   if (carry == 0)
      return result;
   else
      addNumbers(carry, result);
}
int main(){
   int a = 54, b = 897;
   printf("The sum of %d and %d using bitwise adding is %d", a, b, addNumbers(a, b));
   return 0;
}

Output

The sum of 54 and 897 using bitwise adding is 951’
raja
Published on 05-Aug-2020 08:00:22
Advertisements