给定无符号整数,我想知道是否有办法确定是否在单个操作中设置了多个位。已经有一种替代方法可以通过逐位检查来实现这一点(如下所示),但我想知道是否有办法集中检查所有位。
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
}
使用集合方法的示例也如下所示。有任何想法吗? 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
}
答案 0 :(得分:7)
(Value& Foos_to_Check)== Foos_to_Check
答案 1 :(得分:2)
(value & (FOO_0 | FOO_3)) == (FOO_0 | FOO_3)
在设置true
和FOO_0
时返回FOO_3
。
答案 2 :(得分:0)
您可以使用简单的按位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";
}