Thursday, August 28, 2008

How to add two numbers without using arithmetic operators ?

Here is how you can add two numbers without using any arithmetic operators. The code uses bitwise operators. This code pretty much implements a full adder which adds three bits and returns two bits ( a carry and a sum).

A full adder circuit looks like this:
A full adder circuit

In the above diagram A and B are the bits to be added. C is the carry from a previous addition operator if any. S is the sum of the two bits minus the carry and C1 is the new carry which is to be used for further operations.

The truth table for a full adder would look like this:

C A B S C1
0 0 0 0 0
1 0 0 1 0
0 1 0 1 0
1 1 0 0 1
0 0 1 1 0
1 0 1 0 1
0 1 1 0 1
1 1 1 1 1



//This code doesn't include any overflow error checking mechanism. It is not much difficult to implement one however.
#include
int main(){
unsigned num1,num2,result=0,i=0,temp=0;
printf("Enter the two numbers:\n");
scanf("%d",&num1);
scanf("%d",&num2);
for (i= ~0; i; i>>= 1){ //ensure that the body of the loop is executed 8*sizeof(unsigned) times where 8 is the number of bits in a byte. The number of bits in a byte can be more than 8 on some machines.
temp<<= 1;
temp|= (num1^num2^result)&1;
result= ((num1|num2)&result|num1&num2)&1;//to understand this line and the one above take a look at the full adder circuit above
//here temp is the equivalent of S1 in the full adder circuit above and result is the equivalent of C1
num1>>= 1;
num2>>= 1;
}
//the bit order in temp would be in the reverse order. the following code snippet reverses the order
for (i= ~0, result= ~i; i; i>>= 1){
result<<= 1;
result|= temp&1;
temp>>= 1;
}
printf("Sum: %d",result);
return 0;
}


Here is another elegant solution that uses recursion. Uses the same algorithm as the previous code snippet. A simple value substitution would show you how it works.

#include
int add(int a, int b){
if (!a) return b;
else
return add((a & b) << 1, a ^ b);
}

int main(){
printf("Enter the two numbers: \n");
int a,b;
scanf("%d",&a);
scanf("%d",&b);
printf("Sum is: %d",add(a,b));
}


Below is one more way to add two numbers without the arithmetic operators. This method makes use of the asterisk(*) field width specifier in the printf function and use the returned value from printf. Here the printf statement is given with field width operator in format, and the two numbers are given as argument for field widths, hence we are printing a total width of two given integer arguments. The printf function returns the number of characters printed, and here the total number of characters printed will be sum of a and b. The third and fifth arguments are zero length strings because it only needs to print the total width of two integers.
Note that this method only works for unsigned integers.

unsigned add(unsigned a, unsigned b)
{
return printf("%*s%*s", a, "", b,"");
}

1 comments:

Unknown said...

it's concept of half adder...why are you complicating things as full adder.