How to get the nth bit value

Im relatievly new to all bit offsets and C ++.

Let's say I have uint8_t 00100100(36), and I want to check if the 3rd bit is set. Here is the code how im doing it now, in just one bit.

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

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

What is the most elegant way to do this?

+4
source share
3 answers

Checking the bits for a numeric position is one of the right ways to do this, but it makes the code depend on magic numbers, which makes it difficult to read and maintain.

, , , , , .

, , , , :

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)) {
     // ...
}

, .

, :

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
};
+10

, , , n- , :

bool IsBitSet(uint8_t num, int bit)
{
    return 1 == ( (num >> bit) & 1);
}

uint8_t x = 37; //00100101
for (int i = 0; i < 8; ++i)
{
    if ( IsBitSet(x, i) )
        printf("%dth bit is set\n", i);
    else
        printf("%dth bit not set\n", i);
}

:

0th bit is set
1th bit is not set
2th bit is set
3th bit is not set
4th bit is not set
5th bit is set
6th bit is not set
7th bit is not set

, 3 6:

uint8_t x = 36; //00100100
if ( IsBitSet(x, 2) || IsBitSet(x, 5) )
    printf("bit 3 and/or bit 6 is set\n");

inline .

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

or if you know hex:

uint8_t x = 36;
if (x & 0x24)
    printf("is set");
0
source

All Articles