Home > Backend Development > C++ > body text

Bitwise recursive addition of two integers in C

WBOY
Release: 2023-09-05 21:17:03
forward
1155 people have browsed it

Bitwise recursive addition of two integers in C

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

The logic of summing using bitwise operations is similar to what we did in preschool. To sum, we usually add each digit of the number, and if a carry is present, we add it to the next number.

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

This is the logic of a Half Adder that you may have learned in digital electronics. See here...

Now the sum is calculated using a^b i.e. XOR b, if the first bit of both is set we need to check if extra carry needs to be propagated. We need to add an extra setting bit to the number.

So the bitwise arithmetic will be

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

Step 2 - Check if {(a & b)

Step 2.1 - If equal to 0, Then print the result, which is the final result.

Step 2.2 - If not equal to 0 equals 0, then go to step 1 where a = {(a & b)

Example

Procedural algorithm that illustrates how this function works -

Live demonstration

#include 
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;
}
Copy after login

Output

The sum of 54 and 897 using bitwise adding is 951’
Copy after login

The above is the detailed content of Bitwise recursive addition of two integers in C. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!