Checking bits by numeric position is one of the correct ways to do so but it makes the code depend on magic numbers, which makes it harder to read and maintain.
Usually, when checking for bitmasks, there is a goal of checking for some specific flag, let's say a hardware register for example.
Imagine for example that each bit of your integer represents a specific light in your house, and you want to check whether the bathroom and the kitchen are on:
enum LightMask {
ENTRANCE = 0x01,
LIVING_ROOM = 0x02,
RESTROOM = 0x04,
KITCHEN = 0x08,
BATHROOM = 0x10,
BEDROOM1 = 0x20,
BEDROOM2 = 0x40,
ATTIC = 0x80
};
uint8_t lightsOn = GetLightsOn();
if (lightsOn & (BATHROOM | KITCHEN)) {
// ...
}
This is elegant, easy to understand and can be modified pretty easily.
The enum could also be expressed in terms of bit shifting at no cost for the compiler if you want to explicitely use bit positions instead of constants:
enum LightMask {
ENTRANCE = 1 << 0,
LIVING_ROOM = 1 << 1,
RESTROOM = 1 << 2,
KITCHEN = 1 << 3,
BATHROOM = 1 << 4,
BEDROOM1 = 1 << 5,
BEDROOM2 = 1 << 6,
ATTIC = 1 << 7
};