How to convert a range subset of bits in a C++ bitset to a number? -
this question has answer here:
i have std::bitset
, bitset type provides to_ulong
method translate bitset number, problem translating bitset number while considering range in bitset, need implement own powerof2 function or there more standard approach ?
you can drop unnecessary bits like
#include <bitset> #include <iostream> // drop bits outside 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 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, middle bit }
live example output.
Comments
Post a Comment