2014-09-25 46 views
3

給出一個無符號整數,我想知道是否有一種方法來確定是否在單個操作中設置了多個位。現在已經有一種通過逐位檢查來做到這一點的替代方法(如下所示),但我想知道是否有辦法一起檢查所有的位。如何共同檢查位是否設置爲無符號整數?

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

不要忘記,如果檢查失敗,返回'FALSE'。或者,除非你是一個非常冗長冗長的支持者,否則減少函數體來返回Value&Foo_to_Check; – 2014-09-25 12:46:50

回答

7

(值& Foos_to_Check)== Foos_to_Check

2
(value & (FOO_0 | FOO_3)) == (FOO_0 | FOO_3) 

返回trueFOO_0FOO_3都被設置。

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"; 
} 

Example

相關問題