Last active
August 11, 2018 06:22
-
-
Save YonatanKra/a4d059a115aa00cadb3620df364615de to your computer and use it in GitHub Desktop.
BitwiseAND
This file contains 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
function BitwiseAND(operand1, operand2) { | |
// convert to binary | |
let binary1 = (operand1 >>> 0).toString(2); | |
let binary2 = (operand2 >>> 0).toString(2); | |
// pad with zeros to the left to get 32bit binary | |
binary1 = binary1.padStart(32, '0'); | |
binary2 = binary2.padStart(32, '0'); | |
// if bigger than 32 bits, cut the most significant bits | |
binary1.length > 32 ? binary1 = binary1.slice(binary1.length-32); | |
binary2.length > 32 ? binary2 = binary2.slice(binary2.length-32); | |
//init an empty result string | |
let result = ''; | |
// Go over the strings - they are are both 1, set 1. Otherwise, set 0 | |
for (var i = 0; i < binary1.length; i++) { | |
if (Number(binary1[i]) && Number(binary2[i])) { | |
result += '1'; | |
} else { | |
result += '0'; | |
} | |
} | |
return parseInt(result, 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment