Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check, if bitmask contains bit?

Tags:

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?

like image 299
Nicolai Avatar asked Jan 23 '13 12:01

Nicolai


People also ask

How do you check bit is set or not?

Method 1 (Using Left Shift Operator) 1) Left shift given number 1 by k-1 to create a number that has only set bit as k-th bit. temp = 1 << (k-1) 2) If bitwise AND of n and temp is non-zero, then result is SET else result is NOT SET.

Is bitmask and bit manipulation same?

Bitmasks are a type of bit manipulation, usually performed using the bitwise AND operator to read or clear a specific number of bits. It can also refer to setting, clearing, and toggling individual bits in a bit field.

What is bit masking?

Bit masking is simply the process of storing data truly as bits, as opposed to storing it as chars/ints/floats. It is incredibly useful for storing certain types of data compactly and efficiently. The idea for bit masking is based on boolean logic.


2 Answers

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.

like image 126
tschmit007 Avatar answered Sep 18 '22 15:09

tschmit007


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 } 
like image 23
Alex Avatar answered Sep 19 '22 15:09

Alex