Monday, 29 January 2007

Bit Evaluation and(&) Flags

I always find myself looking up the syntax for bit manipulation purely because its not something I do that often. An Enum with the “FlagsAttribute” causes my brain to reset and think back to the Z80 days, ahhh TLL and Cyclone. Anyway back to the code

Example
usersServices     =             00111010
VirusScanning = 00010000
Answer of & = 00010000 (VirusScanning)


But what I really want is a true or a false and to use it like this

if (IsBitSet(usersServices, ServiceTypes.VirusScanning) == true)


So I have crafted the following function to work out if the bit is set on an enum. Remember this only works if the enum is constructed correctly and the FlagsAttribute is added.

private static bool IsBitSet(Enum source, Enum lookingFor)
{
int s = Convert.ToInt32(source);
int l = Convert.ToInt32(lookingFor);
if((s & l) == l)
{
return true;
}
return false;
}


Why do the Convert calls, well it turns out that the language support for the "&" cannot be applied to a type of System.Enum.

Any Comments!

Tags