Search code examples
coptimizationbit-shift

Can a modern C compiler optimize a combination of bit accesses?


I would like var to be unequal FALSE in case one of the bits 1, 3, 5, 7, 9, 11, 13 or 15 of input is set.

One solution which seem to be fairly common is this:

int var = 1 & (input >>  1) ||
          1 & (input >>  3) ||
          1 & (input >>  5) ||
          1 & (input >>  7) ||
          1 & (input >>  9) ||
          1 & (input >> 11) ||
          1 & (input >> 13) ||
          1 & (input >> 15);

However, I'm afraid that that would lead the compiler to generate unnecessarily long code.

Following code would also yield the desired result. Would it be more efficient?

int var = input & 0b1010101010101010;

Thanks!


Solution

  • If input is volatile, the compiler would be required to read it once if bit 1 was set, twice of bit 1 was clear but 3 was set, three times if bits 1 and 3 were clear but 5 was set, etc. The compiler may have ways of optimizing the code for doing the individual bit tests, but would have to test the bits separately.

    If input is not volatile, a compiler could optimize the code, but I would not particularly expect it to. I would expect any compiler, however, no matter how ancient, to optimize

    int var = (input & (
      (1 << 1) | (1 << 3) | (1 << 5) | (1 << 7) |
      (1 << 9) | (1 << 11) | (1 << 13) | (1 << 15)
    ) != 0);
    

    which would appear to be what you're after.