How can I clear multiple bits at once in C?

Viewed 2563

How would I simplify all of this into one line?

    REG &= ~BITA;
    REG &= ~BITB;
    REG &= ~BITC;
    REG &= ~BITD;
    REG &= ~BITE;
3 Answers

You can use | (bitwise or) operator.

REG &= ~(BITA | BITB | BITC | BITD | BITE);

@MikeCAT answer is correct and here is bit There is a simple rule A & B = ~A || ~B. so you can extend your problem to:

REG &= ~BITA & ~BITB & ~BITC & ~BITD & ~BITE; // 10 operations

you can reduce it to:

REG &= ~(BITA | BITB | BITC | BITD | BITE);  // 6 operation

This way you factor out common factor to reduce number of operations. You can think of this retuction like math:

A += B * -55 + C * -55 + D * -55
A += -55B - 55C - 55D
A += -55(B + C + D)

To read more about boolean algebra (which is very important in this case click here

If I find any more good reference, I will link it here.

It is also possible to clear bits by position with bit shifting:

REG &= ~((1<<7) | (1<<6) | ...);

or with predefined bit position:

#define BITA 7
#define BITB 6

REG &= ~((1<<BITA) | (1<<BITB) | ...);
Related