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?
As bitset stores the same information in compressed manner the operation on bitset are faster than that of array and vector.
bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1.
C++ bitset count() function is used to count the number of set bits in the binary representation of a number.
Bitset is a container in C++ Standard Template Library for dealing with data at the bit level. 1. A bitset stores bits (elements with only two possible values: 0 or 1). We can however get the part of a string by providing positions to bitset constructor (Positions are with respect to string position from left to right)
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With