Created
February 7, 2014 08:51
-
-
Save wildlyinaccurate/8859257 to your computer and use it in GitHub Desktop.
Bitwise addition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@wildlyinaccurate thank you. I tried to split the input numbers into smaller parts to be able to sum larger numbers but it computes incorrectly.