Skip to content

Instantly share code, notes, and snippets.

@wildlyinaccurate
Created February 7, 2014 08:51
Show Gist options
  • Save wildlyinaccurate/8859257 to your computer and use it in GitHub Desktop.
Save wildlyinaccurate/8859257 to your computer and use it in GitHub Desktop.
Bitwise addition
// Fuck the addition operator. Real programmers work in binary!
function add(a, b) {
// XOR to get the sum of the bits
var sum = a ^ b;
// "Carry" bits are common to both numbers
var carry = (a & b) << 1;
if (sum & carry) {
// Rinse and repeat until there are no leftover bits
return add(sum, carry);
} else {
return sum ^ carry;
}
}
/*
> add(5, 6)
11
> add(5, 10)
15
> add(-1, 40)
39
> add(1, 9)
10
*/
@ozgursar
Copy link

@wildlyinaccurate thank you. I tried to split the input numbers into smaller parts to be able to sum larger numbers but it computes incorrectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment