There's more...

The bitset can be created from an integer and can convert its value to an integer using the to_ulong() or to_ullong() methods. However, if the size of the bitset is larger than the size of these numerical types and any of the bits beyond the size of the requested numerical type is set to 1, then these methods throw an std::overflow_error exception because the value cannot be represented on unsigned long or unsigned long long. In order to extract all the bits, we need to do the following operations, as shown in the next code:

  • Clear the bits beyond the size of unsigned long or unsigned long long.
  • Convert the value to unsigned long or unsigned long long.
  • Shift the bitset with the number of bits in unsigned long or unsigned long long.
  • Do this until all the bits are retrieved.
    template <size_t N>
std::vector<unsigned long> bitset_to_vectorulong(std::bitset<N> bs)
{
auto result = std::vector<unsigned long> {};
auto const size = 8 * sizeof(unsigned long);
auto const mask = std::bitset<N>{ static_cast<unsigned long>(-1)};

auto totalbits = 0;
while (totalbits < N)
{
auto value = (bs & mask).to_ulong();
result.push_back(value);
bs >>= size;
totalbits += size;
}

return result;
}

std::bitset<128> bs =
(std::bitset<128>(0xFEDC) << 96) |
(std::bitset<128>(0xBA98) << 64) |
(std::bitset<128>(0x7654) << 32) |
std::bitset<128>(0x3210);

std::cout << bs << std::endl;

auto result = bitset_to_vectorulong(bs);
for (auto const v : result)
std::cout << std::hex << v << std::endl;

For cases where the size of the bitset cannot be known at compile time, the alternative is std::vector<bool>, which we will cover in the next recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset