How to check if a value exists in a bit-enum?

CinCout

New Member
#1
I have an enum:
Mã:
enum Rule
{
    BIT_NONE,
    BIT_ONE,
    BIT_TWO = 1 << 1,
    BIT_THREE = 1 << 2,
    BIT_FOUR = 1 << 3
};
Now, how do I verify that a specific int value belongs to the above enum? Note that the idea is to also allow any combination of BIT_TWO, BIT_THREE, and BIT_FOUR, ergo the valid values are {0, 1, 2, 4, 6, 8, 10, 12, 14}.

If I check BIT_NONE <= val && val <= BIT_FOUR, it won't permit the combinations as mentioned above, but will also include the unwanted {3, 5, 7}.

How can I achieve that?
 

Admin

Administrator
Thành viên BQT
#2
This needs some bit operation tricks:

To allow all enum as a single bit, you need to be sure it's less than BIT_FOUR, and it's only a single bit. The latter can be detected by !((val-1)&val):
Mã:
bool is_allowed_single(unsigned val) {
    return BIT_NONE <= val && val <= BIT_FOUR && !((val-1)&val);
}
Then combination of certain bits is also valid:
Mã:
bool is_allowed_combination(unsigned val) {
    return !(val & ~(BIT_TWO|BIT_THREE|BIT_FOUR));
}
Finally, we get:
Mã:
bool is_allowed(unsigned val) {
    return is_allowed_single(val) || is_allowed_combination(val);
}
 
Top