Search code examples
c++bitset

comparing sub-bitsets in C++


I have two bitsets std::bitset<200> A and std::bitset<200> B and I would like to compare the bits A[10-60] and B[50-100]. I am extracting the 50 bits in both bitsets into another two bitsets and then comparing them like following. Is there any better approach?

std::bitset<200> A, B;
// A and B are already set
std::bitset<50> x, y;
for(int i=10; i<=60; i++)
  if(A.test(i)) x.set(i);
for(int i=50; i<=100; i++)
  if(B.test(i)) y.set(i);

if( x == y) ....

Solution

  • How about looping both bitsets, A and B, together?

    bool same = true;
    for (size_t ai = 10, bi = 50; ai != 60; ++ai, ++bi) {
      if (A.test(ai) != B.test(bi) {
        same = false;
        break;
      }
    }
    // same denotes if the sections of A and B are equal.