最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

bit manipulation - Bit masking (javascript): how to check ALL flags - Stack Overflow

programmeradmin2浏览0评论

If I have the number '00001000' and the mask '00101000', how can i check, with a binary operation, if both the bits in the number are set? number & mask return true if at least one bit match, but I need to check for all of them to match. How to?

If I have the number '00001000' and the mask '00101000', how can i check, with a binary operation, if both the bits in the number are set? number & mask return true if at least one bit match, but I need to check for all of them to match. How to?

Share Improve this question edited Oct 8, 2015 at 13:08 Salman Arshad 272k84 gold badges442 silver badges534 bronze badges asked Oct 8, 2015 at 13:00 pistacchiopistacchio 58.9k110 gold badges287 silver badges433 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 15

Just pare to the mask:

if ((number & mask) === mask) {
  // all bits are set!
}

The only way the result of the & operation will be exactly the same as the value of the mask is when the number has all the bits set. (The test number may have more bits set; if you want to check to see if it's got exactly the same bits set and unset, then that's a simple equality test.)

发布评论

评论列表(0)

  1. 暂无评论