首页 > 解决方案 > How does `(sum & operand) === operand` work in the following code? (Bitwise And)

问题描述

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))

标签: javascriptalgorithmmathbitwise-operatorsbitwise-and

解决方案


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.


推荐阅读