Skip to content

Instantly share code, notes, and snippets.

@YonatanKra
Last active November 8, 2021 09:09
Show Gist options
  • Select an option

  • Save YonatanKra/c19e36140a9604222cbae1e7cf09d12b to your computer and use it in GitHub Desktop.

Select an option

Save YonatanKra/c19e36140a9604222cbae1e7cf09d12b to your computer and use it in GitHub Desktop.
Bitwise OR
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);
}
@xiongbs

xiongbs commented Nov 8, 2021

Copy link
Copy Markdown

line 17, bitwis OR should one of 1 at least, set 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment