lancery
lancery

Reputation: 678

How to collectively check whether bits are set in an unsigned integer?

Given an unsigned integer, I'd like to know if there's a way to determine whether multiple bits are set in a single operation. There's already an alternative way to do this by checking bit by bit (shown below), but I was wondering if there's 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 too. 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           
}

Upvotes: 3

Views: 305

Answers (3)

jonynz
jonynz

Reputation: 454

( Value & Foos_to_Check ) == Foos_to_Check

Upvotes: 7

Marco A.
Marco A.

Reputation: 43662

You can accomplish this with a simple bitwise and check:

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

Upvotes: 0

Nimelrian
Nimelrian

Reputation: 1716

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

returns true when FOO_0 and FOO_3 are both set.

Upvotes: 2

Related Questions