BoulderBum
Programmer
For a project I'm working on, I want to determine whether an enum marked with a FlagsAttribute is passed to a function as a single enum value.
e.g.
To accomplish the task, I'm checking to see if the enum value log 2 is a whole number:
What I'm wondering, however, is if there might be a more efficient way to determine what I want, either algorithmicly or mathematically (just for fun).
Can anyone see a potential improvement to the process?
e.g.
Code:
//this is should succeed.
MyFunction( MyEnum.SingleValue );
//this should fail
MyFunction( MyEnum.OneValue | MyEnum.OtherValue );
To accomplish the task, I'm checking to see if the enum value log 2 is a whole number:
Code:
private bool IsSingleValueEnum(Enum enumValue)
{
int valAsInt = Convert.ToInt32(enumValue);
//always return true if zero because we assume it's a single value,
//but it doesn't work with the rest of the algorithm
if ((int)valAsInt == 0)
return true;
//we know that a single bit occupies the space that sits in a space
//that is 2 to the N-th power, e.g. 2, 4, 8, 16, 32, etc.
//here we check that we have a whole numer after computing log base 2
double log2OfPermissionType = Math.Log((double)valAsInt, 2.0);
//now we check to see if the result is a whole number (which would indicate
//that we have a single bit value passed in permissionType)
return (log2OfPermissionType - Math.Floor(log2OfPermissionType)) < double.Epsilon;
}
What I'm wondering, however, is if there might be a more efficient way to determine what I want, either algorithmicly or mathematically (just for fun).
Can anyone see a potential improvement to the process?