How do I check, if bitmask contains bit?

╄→гoц情女王★ 提交于 2019-11-29 17:17:23

问题


I don't quite understand this whole bitmask concept.

Let's say I have a mask:

var bitMask = 8 | 524288;

I undestand that this is how I would combine 8 and 524288, and get 524296.

BUT, how do I go the other way? How do I check my bitmask, to see if it contains 8 and/or 524288?

To make it a bit more complex, let's say the bitmask I have is 18358536 and I need to check if 8 and 524288 are in that bitmask. How on earth would I do that?


回答1:


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.




回答2:


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
}



回答3:


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



来源:https://stackoverflow.com/questions/14479981/how-do-i-check-if-bitmask-contains-bit

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