nada
nada

Reputation: 2117

Convert uint64_t Bitmask to std::array of bool

The objective is to convert a std::uint64_t (which is used as a bitmask), to a std::array<bool>.

This question is similar to the C# question How can I convert an int to an array of bool?, but for C++ and I'm looking for the algorithm with the bestest performance.

Given a std::uint64_t, which is used as a bitmask, I know it is possible to just loop over its content bitwise & bitcompare set the values to the ones at the same position in the std::array<bool>.

But in almighty C++ there has to be a more efficient way! Maybe some dirty casts, mallocs or whatnot? Everything is ok; I am on Windows / GCC, so even GCC-only features are totally allowed.

Upvotes: 0

Views: 889

Answers (1)

NathanOliver
NathanOliver

Reputation: 180955

If you just need random access to the individual bits you can use a std::bitset instead of a std::array. That would look like

uint64_t mask = some_value;
std::bitset<64> random_access(mask);

// and now you can use random_access[some_index]

std::bitset does lack begin() and end() members though, so you can't use it with a ranged based for loop as-is. You can however iterate over a std::bitset using a regular index based for loop like

for (size_t i = 0; i < random_access.size(); ++i)
    std::cout << random_access[i] << "\n";

Upvotes: 6

Related Questions