Search code examples
cgccbooleanbitwise-operators

Comparing a bit to a boolean


Say I have a set of flags, encoded in a uint16_t flags. For example, AMAZING_FLAG = 0x02. Now, I have a function. This function needs to check if I want to change the flag, because if I want to do that, I need to write to flash. And that is expensive. Therefore, I want a check which tells me if flags & AMAZING_FLAG is equal to doSet. This is the first idea:

setAmazingFlag(bool doSet)
{
    if ((flags & AMAZING_FLAG) != (doSet ? AMAZING_FLAG : 0)) {
        // Really expensive thing
        // Update flags
    }
}

This is not an intuitive if statement. I feel like there should be a better way, something like:

if ((flags & AMAZING_FLAG) != doSet){

}

But this does not actually work, true seems to be equal to 0x01.

So, is there a neat way to compare a bit to a boolean?


Solution

  • To convert any non-zero number to 1 (true), there is an old trick: apply the ! (not) operator twice.

    if (!!(flags & AMAZING_FLAG) != doSet){