How do I check, if bitmask contains bit?

39,523

Solution 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.

Solution 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
}

Solution 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

Share:
39,523
Nicolai
Author by

Nicolai

Updated on July 16, 2022

Comments

  • Nicolai
    Nicolai almost 2 years

    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?

  • Slipp D. Thompson
    Slipp D. Thompson about 7 years
    Alternatively, if ((mask & bitmask) != 0). If find this a bit clearer (perhaps because of the many times I've type != null over the years).
  • Barbz_YHOOL
    Barbz_YHOOL over 3 years
    found this while looking for the SQL question, it helped so here I put the equivalent in SQL SELECT IF(128 & 1101 = 128, "YES", "NO");