Utility function to get a vector of set bits

Template function to return a vector with the positions of all set bits in a variable.
This commit is contained in:
Erik Fröjdh
2020-08-05 13:42:57 +02:00
committed by GitHub
parent 6db5954d21
commit aa0c36713c
5 changed files with 62 additions and 8 deletions

View File

@ -0,0 +1,19 @@
#pragma once
#include <vector>
#include <bitset>
namespace sls {
template <typename T> std::vector<int> getSetBits(T val) {
constexpr size_t bitsPerByte = 8;
constexpr size_t numBits = sizeof(T)*bitsPerByte;
std::bitset<numBits> bs(val);
std::vector<int> set_bits;
set_bits.reserve(bs.count());
for (size_t i = 0; i < bs.size(); ++i) {
if (bs[i]) {
set_bits.push_back(static_cast<int>(i));
}
}
return set_bits;
}
} // namespace sls