I have a problem with flag bits. I have an int
variable to hold flags. First I set some flags to that variable. Later I need check how many flags were set in that variable. But I don't know to do it.
To check a flag state, we use bitwise AND operator (&). It allows to determine if bit is on or off.
The bitwise-AND (&), OR (|), and Ex-OR (^) operators compare two operands bit by bit. The AND (&) operator sets the result bit to 1 only if both the operand bits are 1. The OR (|) operator, on the other hand, sets the result bit to 1 when any one or both the operand bits is 1.
Short Answer You want to do an Bitwise AND operation on the current value with a Bitwise NOT operation of the flag you want to unset. A Bitwise NOT inverts every bit (i.e. 0 => 1, 1 => 0). flags = flags & ~MASK; or flags &= ~MASK; . When you perform a Bitwise AND with Bitwise NOT of the value you want unset.
To check to see if a bit value is set:
int value = VALUE_TO_CHECK | OTHER_VALUE_TO_CHECK; if ((value & VALUE_TO_CHECK) == VALUE_TO_CHECK) { // do something--it was set } if ((value & OTHER_VALUE_TO_CHECK) == OTHER_VALUE_TO_CHECK) { // also set (if it gets in here, then it was defined in // value, but it does not guarantee that it was set with // OR without other values. To guarantee it's only this // value just use == without bitwise logic) }
It's important to note that you should not have a checked value as 0 unless it represents All or None (and don't use bitwise logic to compare; just use value == 0
) because any value & 0
is ALWAYS 0.
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