user1930254 user1930254 - 3 years ago 162
C++ Question

How to get nth bit values

Im relatievly new to the whole bit shifting, and c++.

Let's say i have an

uint8_t 00100100
(36) and i want to check if the 3th bit is set.
Here is the code how im doing it now, for only one bit.

uint8_t x = 36;
if(x&1<<3)
printf("is set");


how can i check if the 3th OR the 6th bit is set? I want to check several combinations of bits like 5th or 7th or 8th.

what is the most elegant way to do it?

Answer Source

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
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download