Javascript Bitwise Operation

I was wondering if there is a way to find out if a given binary pattern, two or more of 1 are within another binary pattern. I say a pattern because the actual value does not determine if it is inside another.

For instance,

0001 1110 0000 0000
0001 1111 0000 0000
--> true

0001 0000 1100 0000
0001 1111 0000 0000
--> false

0001 1100 0000 1000
0001 0000 0000 1111
--> true

0001 1000 1100 0000
0001 0000 0000 1111
--> false

I tried using various AND / OR / XOR / NOT, but not sure how to do it. Please, help!

So the question about data data is as follows:

const RANKS = [
  0b0000000001110001,
  0b0000001001000110,
  0b0001001100000100,
  0b0000000011011000,
];

I am trying to iterate over RANKS to see if it matches the pattern:

const PATTERNS = [
  0b0001111100000000,
  0b0000111110000000,
  0b0000011111000000,
];

Only 2 of 1 from RANK must “match” in PATTERN to be considered true

+4
source share
2 answers

function sharesAtLeastTwoBits(x, y) {
  var a = x & y;
  if (!a) return false;
  while (!(a & 1)) a >>>= 1;
  return a != 1;
}

console.log(sharesAtLeastTwoBits(
  0b0001111000000000,
  0b0001111100000000
))

console.log(sharesAtLeastTwoBits(
  0b0001000011000000,
  0b0001111100000000
))

console.log(sharesAtLeastTwoBits(
  0b0001110000001000,
  0b0001000000001111
))

console.log(sharesAtLeastTwoBits(
  0b0001100011000000,
  0b0001000000001111
))
Run codeHide result

&, , . , false. , 0- ; , 1, 1, false ; true.

: andyg0808 .

+2

and , , , 1. , , . count:

function count(num) {
  var c = 0;
  while (num > 0) {
    if (num & 1) {
      c++;
    }
    num = num >>> 1;
  }
  return c;
}
console.log(count(1)); /* 1 */
console.log(count(2)); /* 1 */
console.log(count(3)); /* 2 */
Hide result

H/T to .

+4

Source: https://habr.com/ru/post/1653744/


All Articles