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?
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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With