Check if multiple bits are set or cleared

3

I wish to check if multiple bits in a 32-bit register are set or cleared for the purpose of manipulating hardware. I adopt the following approach to check if the desired bits (bit 8 and bit 1) of an uint32_t-variable called statusRegister are set:

if ((statusRegister & 0x00000102) == 0x00000102) {}

And the following to check if the wanted bits are cleared:

if ((statusRegister | ~0x00000102) == ~0x00000102) {}

Is this correct? Is there a more concise way of doing it?

c
bit-manipulation
asked on Stack Overflow Jan 24, 2019 by Abdel Aleem • edited Jan 24, 2019 by Abdel Aleem

1 Answer

7

To check whether multiple bits are cleared, you'd typically use this somewhat more concise idiom:

if ((statusRegister & 0x00000102) == 0) {}
// or
if (!(statusRegister & 0x00000102)) {}

You could also check whether multiple bits are set with:

if ((statusRegister | ~0x00000102) == ~0) {}
// or
if (!(~statusRegister & 0x00000102)) {}

But the version in your question is much more common. ANDing with a bitmask is the simplest mental model and easiest to understand for your fellow programmers.

answered on Stack Overflow Jan 24, 2019 by nwellnhof

User contributions licensed under CC BY-SA 3.0