-1

The following code checks if sum has operand, the code is very straightforward, but I'm confused by the condition (sum & operand) === operand.

I've read the Bitwise AND (&) doc, confused me even more, can someone explain it in simple terms?

const has = (sum, operand) => (sum & operand) === operand

console.log(has(7, 4))
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90

1 Answers1

0

This kind of code is usually used when you are working with bitflags. Essentially you want to check if the operand bits are set in the sum aswell.

The binary representation of 7 is 00000111, while the binary representation of 4 is 00000100.

By performing the bitwise AND operation A & B you are "preserving" the identical bits between the two, while setting all other bits to 0. Comparing the result with B again yields you the insight if all bits that are set in B are also set in A.

Ian H.
  • 3,840
  • 4
  • 30
  • 60