I have an std::bitset
and the bitset type also provides a to_ulong
method to translate the bitset into a number, my problem is about translating the bitset into a number while just considering a range in that bitset, I need to implement my own powerof2 function or there is something with a more standard approach ?
bitset set() function in C++ STL 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.
bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits.
Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.
Using Clang 10.0 and GCC 10.1, in both cases the array of bools is faster than bitset.
You can drop the unnecessary bits like
#include <bitset>
#include <iostream>
// drop bits outside the range [R, L) == [R, L - 1]
template<std::size_t R, std::size_t L, std::size_t N>
std::bitset<N> project_range(std::bitset<N> b)
{
static_assert(R <= L && L <= N, "invalid bitrange");
b >>= R; // drop R rightmost bits
b <<= (N - L + R); // drop L-1 leftmost bits
b >>= (N - L); // shift back into place
return b;
}
int main()
{
std::bitset<8> b2(42); // [0,0,1,0,1,0,1,0]
std::cout << project_range<0,8>(b2).to_ulong() << "\n"; // 42 == entire bitset
std::cout << project_range<2,5>(b2).to_ulong() << "\n"; // 8, only middle bit
}
Live example with output.
You can use string
as intermediate storage:
bitset<32> bs (string("1011"));
cout << bs.to_ullong() << endl;
// take a range - 2 last bits in this case
string s = bs.to_string().substr(bs.size() - 2);
bitset<32> bs1 (s);
cout << bs1.to_ullong() << endl;
Prints:
11 3
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