javascript - 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))
解决方案
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
.
推荐阅读
- class - 在类中创建的模块实例如何从此类(Python 3)继承?
- scala - 尝试将 Spark DF 写入 Hive 表时出现错误“对未解析对象的限定符调用无效”
- python - 添加和规范化在熊猫中重复键的行
- python - Python Word Vect numpy 数组,保存到 csv 时出现维度错误,预期 1D 或 2D 数组,改为 0D 数组
- php - 静态属性将如何在队列中工作?
- asp.net-core - 如何使用 Azure Active Directory 在 ASP.NET Core 应用程序中获取经过身份验证的用户的名称
- python - 以毫秒为单位将时间戳传递给由 SQLite3 支持的 SQLAlchemy
- javascript - JavaScript 函数在 Django 上不起作用
- python - 退出程序后输入数据不会立即保存
- android - 使用 RecyclerView 删除 Sqlite 中的行