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?
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.
User contributions licensed under CC BY-SA 3.0