Skip to content

Instantly share code, notes, and snippets.

@nick3499
Created July 14, 2020 18:26
Show Gist options
  • Save nick3499/07c48655d1ebdebba2fcdab15e7eab48 to your computer and use it in GitHub Desktop.
Save nick3499/07c48655d1ebdebba2fcdab15e7eab48 to your computer and use it in GitHub Desktop.
Bitwise Addition of Integers
#! /bin/nodejs
function addBitwise (a, b) {
// if `a` = `3` and `b` = `2`
let c = 0; // carry over
// loop while `b` is not equal to zero
while (b !== 0) {
// first iteration
c = a & b; // bitwise AND: 3/0011 AND 2/0010 --> 2/0010
a ^= b; // bitwise XOR: 3/0011 XOR 2/0010 --> 1/0001
b = c << 1; // shift left bitwise: 3/0011 --> 6/0110
}
return a; // return sum of 3 + 2 = 5
}
console.log(addBitwise(3, 2));
console.log(addBitwise(7, 5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment