I'm working on something that requires me to get access to specific bits and ranges of bits. I decided to use bitset because it is easy to get access to specific bits; how can I extract a range (subset) of bits?
Asked
Active
Viewed 2,503 times
2 Answers
13
Method A:
return (the_bitset >> start_bit).to_ulong();
Method B (faster than method A by 100 times on my machine):
unsigned long mask = 1;
unsigned long result = 0;
for (size_t i = start_bit; i < end_bit; ++ i) {
if (the_bitset.test(i))
result |= mask;
mask <<= 1;
}
return result;

kennytm
- 510,854
- 105
- 1,084
- 1,005
-
2`operator[]` should be faster still since no bounds check as in `test()`. – Ciro Santilli OurBigBook.com May 15 '17 at 21:21
0
One complete example:
#include <bitset>
#include <iostream>
#include <spdlog/spdlog.h>
template<std::size_t FROM, std::size_t TO, std::size_t SIZE>
std::bitset<TO - FROM> subBitSet(std::bitset<SIZE> &fromBitSet) {
std::bitset<TO - FROM> toBitSet;
for (int i = 0; i < TO - FROM; ++i) toBitSet.set(i, fromBitSet[i + FROM]);
return toBitSet;
}
int main() {
std::bitset<8> bitSet("10110000");
std::cout << "BitSet: " << bitSet << std::endl;
std::cout << "(0,4]: " << subBitSet<0, 4>(bitSet) << std::endl;
std::cout << "(2,6]: " << subBitSet<2, 6>(bitSet) << std::endl;
std::cout << "(4,8]: " << subBitSet<4, 8>(bitSet) << std::endl;
}
The output
BitSet: 10110000
(0,4]: 0000
(2,6]: 1100
(4,8]: 1011

BaiJiFeiLong
- 3,716
- 1
- 30
- 28