Is there any performance loss/gain using bitset in place where hand written?
How to build the following using a bitset at runtime
- make all the bits between 2 and 5 as zero i.e.,
11110011
.
Is there any performance loss/gain using bitset in place where hand written?
How to build the following using a bitset at runtime
11110011
.For a simple example such as the above, a decent hand-coded solution will be faster than using bitset, but the performance differences in either case would be small.
The golden rule:
Don't optimise prematurely!
Bitset will in 99% of cases, be fast enough, and has the advantage of being a common concept such that it's both more readable, and less prone to implementation errors. Don't simply assume that your code will obviously need the speed increase; write the code using bitset, profile your application, and see if:
Per the 80-20 rule, chances are that you'll get a much greater return on making some other bit of code faster. And hey, if it turns out that you do need to improve the bit-twiddling speed, at least you have some decent baseline figures to use in order to show that you r solution really is faster than the default (which you'd need anyway if you wanted to optimise for performance).
The easiest solution to your second question would be to use another bitset.
void makebitszero(bitset<8>& b) {
// Everything but bits 3 and 4 (between 2 and 5).
static const bitset<8> mask = ~bitset<8>(12);
b &= mask;
}
It takes a bit of math to come up with an expression for mask
given two bit positions.
[edit]
Ok, here's the math. The trick is that (1UL << X) -1
is a sequence of X
ones. E.g. 3 => 00000111.
Hence, (1<<5) - (1<<3) = 00011111 - 00000111 -1 + 1 = 00011000 (bits 3 and 4). Thus in code:
template<int i, int j, int N>
void makeBitsZero(bitset<N>& b) {
// Everything from bit i up to but not including bit j (i < j)
static const bitset<N> mask = ~bitset<N>(1UL<<j) - (1UL<<i));
b &= mask;
}