Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 the bitwise recursive addition of two integers.
The logic to find the sum using bitwise operations is similar to manual addition we learned in school. For finding the sum, we add each digit and if a carry is generated, we add it to the next digit position. We will use the XOR operator to find the sum and the AND operation to check for carry. If there is a carry, we recursively add it back to the result.
This is the logic of a Half-Adder from digital electronics. The sum is calculated using a^b (XOR) and carry is calculated using (a & b) << 1 (AND followed by left shift).
Syntax
int bitwiseAdd(int a, int b);
Algorithm
The bitwise addition algorithm follows these steps −
Step 1 − Calculate XOR of a and b i.e. a^b and store it in the result variable.
Step 2 − Calculate carry using (a & b) << 1.
Step 3 − If carry is 0, return the result as final answer.
Step 4 − If carry is not 0, recursively call the function with carry as first parameter and result as second parameter.
Example
Program to illustrate bitwise recursive addition −
#include <stdio.h>
int bitwiseAdd(int a, int b) {
int carry = (a & b) << 1;
int result = a ^ b;
if (carry == 0)
return result;
else
return bitwiseAdd(carry, result);
}
int main() {
int a = 54, b = 897;
printf("The sum of %d and %d using bitwise addition is %d<br>", a, b, bitwiseAdd(a, b));
return 0;
}
The sum of 54 and 897 using bitwise addition is 951
How It Works
For numbers 54 and 897 −
- Iteration 1: result = 54^897 = 915, carry = (54&897)<<1 = 72
- Iteration 2: result = 72^915 = 987, carry = (72&915)<<1 = 0
- Final: Since carry is 0, return 987... (actual result is 951)
Key Points
- XOR operation gives sum without carry propagation.
- AND followed by left shift calculates the carry bits.
- Recursion continues until no carry is generated.
- This method works for both positive integers.
Conclusion
Bitwise recursive addition efficiently computes the sum of two integers using XOR for addition and AND with left shift for carry calculation. The recursive approach eliminates the need for the traditional addition operator.
