Saturday, August 30, 2008

Adding two numbers using bitwise operators without using +

You should know how an half adder works for reading this code.

http://en.wikipedia.org/wiki/Adder_(electronics)
gives info on half adder.


Lets start. If you know half adder you would know that it has an xor gate and an add gate. It manipulates two bits to find a sum and carry.

An addition problem is just the same for 2 power(n) bit number.

ie. Each bit in the first number is Xored with corresponding bit in the other number and a carry is got.

How do we get the carry?? The carry for all the bits is got in another number.

What would you do with this carry. You would try to xor it with the next higher bit in the number.

When do you need to stop all this.. When there's no carry...


here's the c code

int add(int x, int y) {

int a, b;

do {

a = x & y; b = x ^ y; x = a << 1; y = b;

}while(a);

return b;

}

You can also write a recursive code for this

int add(int a,int b)
{
if (!b)

{
return(add((a^b),(a&b)<<1));
}
}