Created
July 14, 2020 18:26
-
-
Save nick3499/07c48655d1ebdebba2fcdab15e7eab48 to your computer and use it in GitHub Desktop.
Bitwise Addition of Integers
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
#! /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