Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking flag bits java

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.

like image 720
Nagaraju Avatar asked May 20 '11 04:05

Nagaraju


People also ask

How do you know if a bit flag is set?

To check a flag state, we use bitwise AND operator (&). It allows to determine if bit is on or off.

How do you compare bits in Java?

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.

How do you clear a flag bit?

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.


1 Answers

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.

like image 164
pickypg Avatar answered Sep 16 '22 14:09

pickypg