Last active
November 8, 2021 09:09
-
-
Save YonatanKra/c19e36140a9604222cbae1e7cf09d12b to your computer and use it in GitHub Desktop.
Bitwise OR
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
| 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
line 17, bitwis OR should one of 1 at least, set 1