Let’s say I have the following
int susan = 2; //0010
int bob = 4; //0100
int karen = 8; //1000
and I pass 10 (8 + 2) as a parameter to a method and I want to decode this to mean susan and karen
I know that 10 is 1010
but how can I do some logic to see if a specific bit is checked as in
if (condition_for_karen) // How to quickly check whether effective karen bit is 1
Right now all i can think of is to check whether the number i passed is
14 // 1110
12 // 1100
10 // 1010
8 // 1000
When I have a larger number of actual bits in my real world scenario, this seems impractical, what is a better way using a mask to just check whether or not I meet the condition for just karen?
I can think of shifting left then back then shifting right then back to clear bits other than the one I’m interested in, but this also seems overly complex.
The traditional way to do this is to use the
Flagsattribute on anenum:Then you’d check for a particular name as follows:
Logical bitwise combinations can be tough to remember, so I make life easier on myself with a
FlagsHelperclass*:This would allow me to rewrite the above code as:
Note I could also add
Karento the set by doing this:And I could remove
Susanin a similar way:*As Porges pointed out, an equivalent of the
IsSetmethod above already exists in .NET 4.0:Enum.HasFlag. TheSetandUnsetmethods don’t appear to have equivalents, though; so I’d still say this class has some merit.Note: Using enums is just the conventional way of tackling this problem. You can totally translate all of the above code to use ints instead and it’ll work just as well.