How do I check, if bitmask contains bit?

Nicolai picture Nicolai · Jan 23, 2013 · Viewed 33.7k times · Source

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?

Answer

tschmit007 picture tschmit007 · Jan 23, 2013

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.