简体   繁体   中英

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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM