Skip to content

Instantly share code, notes, and snippets.

@oclero
Created November 22, 2024 14:38
Show Gist options
  • Select an option

  • Save oclero/9b373d0778ce702582a023aada31eb5e to your computer and use it in GitHub Desktop.

Select an option

Save oclero/9b373d0778ce702582a023aada31eb5e to your computer and use it in GitHub Desktop.
Create a std::bitset from an initializer_list<bool>
// NB: The first value in the list is the smallest bit (a.k.a "little endian").
template<int Size>
constexpr auto make_bitset(const std::initializer_list<bool> &boolean_list) {
auto bits = 0ul;
auto mask = 1ul;
for (auto boolean : boolean_list) {
bits |= boolean ? mask : 0ul;
mask <<= 1;
}
return std::bitset<Size>{bits};
}
// Usage
// -----
// Will give: {1, 0, 1, 0, 0, 1, 1}
constexpr auto values = detail::make_bitset<7>({
true,
true,
false,
false,
true,
false,
true,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment