Skip to content

Instantly share code, notes, and snippets.

@ankitdbst
Created June 26, 2012 16:00
Show Gist options
  • Save ankitdbst/2996680 to your computer and use it in GitHub Desktop.
Save ankitdbst/2996680 to your computer and use it in GitHub Desktop.
Adds two nums without '+' operation. (Works for positives only)
/*
* Addition using bitwise operations
*/
int binary_adder(int a, int b)
{
int sum = 0, pos = 0;
bool bit = 0, carry = 0;
while(a || b) {
// At each position i bitwise sum is the xor
// of bit of a,b at i and carry over
bit = (a^b)&1 ^ carry;
// Carry over occurs when both bits are set or
// atleast one of them is set with a previous carry
carry = (a&b)&1 | (a|b)&carry;
a >>= 1;
b >>= 1;
// If the bit is set we add to sum.
sum |= bit << pos;
pos++;
}
// Finally if there is a carry over we add to sum.
sum |= carry << pos;
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment