Created
December 23, 2024 14:35
-
-
Save romanbsd/d18c511fa4eb7cbd4c4cf8d4350255de to your computer and use it in GitHub Desktop.
Convert bitset to vector<T>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T, size_t BitsetSize> | |
std::vector<T> bitsetToVector(const std::bitset<BitsetSize>& bitset, size_t bitsPerElement = sizeof(T) * 8) { | |
static_assert(std::is_unsigned<T>::value, "Output vector type must be an unsigned integer type."); | |
static_assert(BitsetSize % (sizeof(T) * 8) == 0, "Bitset size must be a multiple of the element size."); | |
size_t numElements = BitsetSize / bitsPerElement; // Calculate number of elements in the output vector | |
std::vector<T> result(numElements); | |
for (size_t i = 0; i < numElements; ++i) { | |
T value = 0; | |
for (size_t j = 0; j < bitsPerElement; ++j) { | |
if (bitset.test(i * bitsPerElement + j)) { // Check if the bit is set | |
value |= (T(1) << j); // Set the corresponding bit in the value | |
} | |
} | |
result[i] = value; // Store the packed value in the vector | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment