Wednesday, 9 February 2011

Add two unsigned integers without using '+'

I found this very interesting discussion (and the program) to add two numbers without the use of the arithmetic operator '+'. The obvious guess would be to use the Bitwise operators.

The logic behind the addition operation using the bitwise operators is as follows:


integer1 =  3  = 0011b
integer2 = 5 = 0101b

first operation second operation third operation
0011 0011
shift by one
0101 0101

______ ______
XOR 0110 AND 0001 ------> <<1 0010

Again...
first operation second operation third operation
previous XOR 0110 0110 shift by one
previous <<1 0010 0010
______ ______
XOR 0100 AND 0010 ------> <<1 0100

Again...
first operation second operation third operation
previous XOR 0100 0100 shift by one
previous <<1 0100 0100
______ ______
XOR 0000 AND 0100 ------> <<1 1000

Again...
first operation second operation
previous XOR 0000 0000
previous <<1 1000 1000
______ ______
XOR 1000 AND 0000
When AND iguals 0 the result of XOR is iqual to the sum of the two integers

The program is as follows:



//Program to add two numbers by using boolean operators
//Ref: http://www.daniweb.com/forums/thread84950.html
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

unsigned long
add(unsigned integer1, unsigned integer2)
{

unsigned long
xor, and, temp;

and
= integer1 & integer2; /* Obtain the carry bits */
xor
= integer1 ^ integer2; /* resulting bits */

while
(and != 0 ) /* stop when carry bits are gone */
{

and
<<= 1; /* shifting the carry bits one space */
temp = xor ^ and; /* hold the new xor result bits*/
and
&= xor; /* clear the previous carry bits and assign the new carry bits */
xor
= temp; /* resulting bits */
}

return
xor; /* final result */
}


int
main()
{

int
num1 = 13, num2 = 27;

cout << num1 << " + " << num2 << " = " <<add(num1, num2) << endl;

return
0;
}



The output is:
13 + 27 = 40

See the original discussion here.

No comments:

Post a Comment