How do I check, if bitmask contains bit?

泄露秘密 提交于 2019-11-30 11:16:09

well

if (8 & bitmask == 8 ) {
}

will check if the bitmask contains 8.

more complex

int mask = 8 | 12345;
if (mask & bitmask == mask) {
   //true if, and only if, bitmask contains 8 | 12345
}

if (mask & bitmask != 0) {
   //true if bitmask contains 8 or 12345 or (8 | 12345)
}

may be interested by enum and more particularly FlagsAttibute.

I'm pretty sure (A & B)==B where A is the bitmask and B is whatever you want to check should do.

Example:

if((18358536 & 8) == 8) 
{
    // mask contains 8
}
Astrus

First of all, bitmasks are for operating on bits, not integers. It is much easier to understand when we deal with just 1's and 0's than more complex numbers.

So for example:

1000110000010000100001000 = 18358536 // in binary.

0000010000000000000000000 = 524288   // in binary.

0000000000000000000001000 = 8        // in binary.

0000010000000000000001000 = 524296   // in binary.

With this, it is clear that integer 8 is a 4th bit from the right side and no other bits marked, so when we add 8 to 524288 (20th bit only) we are simply marking 4th and 20th bits as being true. So we can use the same space in memory reserved for an integer to hold multiple flags that define some boolean properties.

As Alex already explained, you can then check if any flag is available in bitmask by using bitwise AND operator:

if ((mask & flag) == flag) { /* mask has flag set as true */ }

You can read everything about bitmasks in this article

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!