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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With