4

How would I simplify all of this into one line?

    REG &= ~BITA;
    REG &= ~BITB;
    REG &= ~BITC;
    REG &= ~BITD;
    REG &= ~BITE;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
innyme
  • 59
  • 1
  • 7
  • Any C textbook should cover how to set, clear, toggle and test bits. Also imagine it in binary: Ones on the right side keep the bit value, zeroes clear the bit value. Just use as many bits as you like, but not more than the left side can store. – U. Windl Aug 27 '20 at 13:41
  • This is a mega duplicate. Why was it answered? It should have been closed. What is the canonical question? – Peter Mortensen Sep 13 '22 at 09:11
  • Some candidates: *[How to replace bits in a bitfield without affecting other bits using C (2011)](https://stackoverflow.com/q/5925755)*, and *[How do you set only certain bits of a byte in C without affecting the rest?](https://stackoverflow.com/q/4439078)* (2010) – Peter Mortensen Sep 13 '22 at 10:47

3 Answers3

11

You can use | (bitwise or) operator.

REG &= ~(BITA | BITB | BITC | BITD | BITE);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

@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.

  • Reduction of operations can also be done during optimization at compile time. Sometimes it is better to write extended (more) instructions in cause of better readiness. Reduction of processing operations will only happen if the bits are not changed during runtime. If the bits are constant the preprocessor will change `~((1<<7) | (1<<6))` to `0b0011_1111` so the operation `REG &= ~(BITA | ...)` will take around 3 instructions after compiling. – sunriax Aug 03 '20 at 16:36
  • @sunriax I agree Idk what compiler is OP using? And I kind of extended on MikCAT's answer –  Aug 03 '20 at 22:18
  • Is reduction standard? –  Aug 03 '20 at 22:28
  • i can not exactly say that every preprocessor simplifies constants automatically and compiler do optimization, but in environments i use `optimization level (O1)` is mostly turned on. – sunriax Aug 03 '20 at 22:43
  • @sunriax in essence I do agree with it. –  Aug 04 '20 at 20:28
0

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) | ...);
sunriax
  • 592
  • 4
  • 16