25

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?

Nicolai
  • 2,835
  • 7
  • 42
  • 52

3 Answers3

48

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.

tschmit007
  • 7,559
  • 2
  • 35
  • 43
  • 1
    Alternatively, `if ((mask & bitmask) != 0)`.  If find this a bit clearer _(perhaps because of the many times I've type `!= null` over the years)_. – Slipp D. Thompson Mar 16 '17 at 13:16
  • 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");` – Barbz_YHOOL Feb 11 '21 at 20:35
10

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
}
Alex
  • 23,004
  • 4
  • 39
  • 73
7

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

Yes Barry
  • 9,514
  • 5
  • 50
  • 69
Astrus
  • 1,412
  • 1
  • 12
  • 9