How to jointly check if the bits are set to an unsigned integer?
Given an unsigned integer, I would like to know if there is a way to determine if multiple bits are set in one operation. There's already an alternative way to do this by checking bit by bit (shown below), but I was wondering if there is a way to check all the bits collectively.
typedef enum Foo_X
{
Foo_0 = 0x1,
Foo_1 = 0x2,
Foo_2 = 0x4,
Foo_3 = 0x8,
} Foo_X;
bool CheckFoo ( UINT Value, Foo_X Foo_to_Check )
{
if (Value & Foo_to_Check)
{
// Foo_to_Check is present
return true;
}
}
void main()
{
UINT value = GetValueFromSomewhere();
if (CheckFoo(value, Foo_0) && CheckFoo(value, Foo_3))
// both Foo_0 and Foo_3 are present
else
// not both present
}
An example of using the collective method is shown below. Any ideas? TIA!
bool CheckFooTogether ( UINT Value, UINT Foos_to_Check )
{
// check value against Foos_to_Check collectively
}
void main()
{
UINT value = GetValueFromSomewhere();
if (CheckFooTogether (value, Foo_0 | Foo_3))
// both Foo_0 and Foo_3 are present
else
// not both present
}
+3
source to share
3 answers
You can accomplish this with a simple bitwise check and
:
bool CheckFooTogether ( UINT Value, UINT Foos_to_Check )
{
// check value against Foos_to_Check collectively
if( (Value & Foos_to_Check) == Foos_to_Check)
return true;
else
return false;
}
int main()
{
UINT value = Foo_3 | Foo_2;
if (CheckFooTogether (value, Foo_0 | Foo_3))
// both Foo_0 and Foo_3 are present
cout << "both present";
else
// not both present
cout << "not both present";
}
0
source to share