Search code examples
c++bit

Check multiple bits in bitset


I got the following code:

static int P, m, p, M;
static std::bitset<99> B;

p = B[m] & B[m + 5] & B[m + 6] & B[m + 11];

m -= d * (l > 0) * 11 + !d * (c % 5 > 0);

p += m ^ M ? B[m] & B[m + 5] & B[m + 6] & B[m + 11] : 0;

I know it's hard to read, but here's a TL;DR for it: I check multiple bits (all are related to m) in a bitset, then I change the value of variable m and I check again (other bits).

Is there a way i can access those bits in less code, or to template the check (cuz are the same formulas for bits)?

B[m] & B[m + 5] & B[m + 6] & B[m + 11]

Thank you :D.


Solution

  • I suggest using a function to precompute a helper bitset for that:

    bitset<99> prepare_bitset(const bitset<99>& B)
    {
       return B & (B<<5) & (B<<6) & (B<<11);
    }
    

    Then you can just use it like this:

    auto HB = prepare_bitset(B);
    p = HB[m];
    m -= d * (l > 0) * 11 + !d * (c % 5 > 0);
    p += m ^ M ? HB[m] : 0;
    

    UPD: Another option is to just define HB in place:

    auto HB = B & (B<<5) & (B<<6) & (B<<11);
    p = HB[m];
    m -= d * (l > 0) * 11 + !d * (c % 5 > 0);
    p += m ^ M ? HB[m] : 0;