I have a (cyclic) bitset<N> and would like to retrieve the substring i...i+K-1 (where it could happen that i = N - 1; K = 5, so it has to wrap around and get N-1; 0; 1; 2; 3), as another bitset<K> (K is of course known at compile-time)
The obvious thing doesn’t work because operator & doesn’t allow operands of different sizes (although it would be trivial?)
bitset<N> data = ...;
bitset<K> mask; mask = ~mask;
bitset<K> rotated = in << i | in >> (K - i);
bitset<K> slice = rotated & mask;
The next best thing doesn’t work with large N
bitset<K> slice( rotated.to_ullong() & mask.to_ullong() );
What to do, short of implementing bitset<min<N,K>::value> operator &(bitset<N>,bitset<K>)? (and maybe not as terribly inefficient, this approach copies the set 3 times)
As you’ve seen none of the bitset public member functions support copying between bitsets of different sizes. The convert to ulong function isn’t useful if you have sets that won’t fit in a ulong. I don’t see why the standard couldn’t at least have a copy constructor and assignment operator that supported different sizes. That said given the standard class I don’t see any way around copying the bits one at a time.
I’d suggest something like the following:
template〈size_t D_SZ,size_t S_SZ〉 void CopyBitset(std::bitset〈D_SZ〉 &dest, const std::bitset〈S_SZ〉 &source,size_t idx, size_t count,size_t destidx=0) { for(size_t i = 0; i != count;++i){ dest.set((i + destidx) % D_SZ, source[(i + idx) % S_SZ]); } }At least the shift and copy operations are combined.
You might also take a look at boost’s dynamic bitset to see if it would more closely match your usage .