Write a function that accepts two unsigned int and return sum of these two integers. The function should not use any arithmetic operator (mayuse bitwise operators only).
Solution:
Using Bitwise operator we can find the Sum-bit of two bits using the XOR operator and Carry-bit using AND operator, as shown below in the truth table
x y SUM CARRY -- -- --- ----- 0 0 0 0 0 1 1 0 1 0 1 0 1 1 0 1
We can extend this logic (of adding two bits) for large integers. We use the fact that if the two integers have different bits at same positions then XOR (^) will return Sum of these two integers and there will be no carry
a = 5 = 0101 b = 10 = 1010 ------------- XOR = 1111 = 15 (5+10)
If there are some Common bits, then we can have a combined carry (carry of all the common bits) by taking Bitwise-AND of two numbers. Hence the Algo can be
sum = a; while(b != 0) carry = a AND b sum = sum XOR b b = carry << 1 // Because Carry of position i' gets added to (i+1)
Code:
unsigned int add(unsigned int a, unsigned int b) { while (b != 0) { int carrb = a & b; a = a ^ b; b = carrb << 1; } return a; }
1 Comment
hi i am looking the code for adding two integers without using the arithmetic operator here i found the complete information thank you for giving this type of information give some more updates about C language thanks
I am a professional blogger, present started writing artilces on administrative assistant job description