Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multiple bits are set or cleared

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?

like image 992
Abdel Aleem Avatar asked Jan 24 '19 09:01

Abdel Aleem


1 Answers

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.

like image 174
nwellnhof Avatar answered Oct 19 '22 17:10

nwellnhof