Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of two numbers with bitwise operator

I am pasting the code to find the sum of two numbers with bitwise operator. Please suggest if it can be optimized. Thanks...

public static int getSum(int p, int q)
{
int carry=0, result =0;
for(int i=0; i<32; i++)
{
    int n1 = (p & (1<<(i)))>>(i); //find the nth bit of p
    int n2 = (q & (1<<(i)))>>(i); //find the nth bit of q

    int s = n1 ^ n2 ^ carry; //sum of bits
    carry = (carry==0) ? (n1&n2): (n1 | n2); //calculate the carry for next step
    result = result | (s<<(i)); //calculate resultant bit
}

return result;
}
like image 472
Trying Avatar asked Mar 10 '13 20:03

Trying


People also ask

How do you add two binary numbers using bitwise operators?

If x and y don't have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.

How do you add bitwise operators?

Bitwise add using Recursion Adding the numbers using the bitwise operators can also be done in a recursive manner. The same logic takes place but instead of a loop, we use a recursive function to do the Addition. In this code, a^b is the sum expression, and (a&b) << 1 is the carry expression after shifting.


2 Answers

Think in entire bits:

public static int getSum(int p, int q)
{
    int result = p ^ q; // + without carry 0+0=0, 0+1=1+0=1, 1+1=0
    int carry = (p & q) << 1; // 1+1=2
    if (carry != 0) {
        return getSum(result, carry);
    }
    return result;
}

This recursion ends, as the carry has consecutively more bits 0 at the right (at most 32 iterations).

One can easily write it as a loop with p = result; q = carry;.

Another feature in algorithmic exploration is not going too far in differentiating cases. Above you could also take the condition: if ((result & carry) != 0).

like image 105
Joop Eggen Avatar answered Oct 13 '22 11:10

Joop Eggen


I think that the optimizations should be in the field of readability, rather than performance (which will probably be handled by the compiler).

Use for loop instead of while

The idiom for (int i=0; i<32; i++) is more readable than the while loop if you know the number of iterations in advance.

Divide the numbers by two

Dividing the numbers by two and getting the modulu:

n1 = p % 2;
p  /= 2;

Is perhaps more readable than:

(p & (1<<(i-1)))>>(i-1);
like image 20
Adam Matan Avatar answered Oct 13 '22 10:10

Adam Matan