Whether you like it or not, you'll need special handling for the
first and the last array element involved, with if
.
Basically, you have to convert your first and last into
bit-number/array index pairs, and work from there. To mask out
everything but the designated range, you zap everything beloe
the first array index, and after the last (probably using
std::fill
), and special handle the elements at the first and
last array index (which may be the same, which in turn entails
special handling, different from the case where they are
different). Very roughly (and without any error handling):
// quot is element index,
// rem is bit number in element.
div_t first = div( firstBitNumber, bitsInWord );
div_t last = div( lastBitNumber, bitsInWord );
std::fill( array.begin(), array.begin() + first.quot, 0 );
if ( first.quot == last.quot ) {
array[ first.quot ] &= ((1 << last.rem) - 1) & ~((i << first.rem) - 1);
} else {
array[ first.quot ] &= ~((i << first.rem) - 1);
array[ last.quot ] &= ((1 << last.rem) - 1);
}
std::fill( array.begin() + last.quot + 1, array.end(), 0 );
You'll probably need some casts with the shift operators, in
order to ensure they use the full size of the array elements.
And of course, you definitely want to ensure that first and last
are in bounds before any of this.