Created
November 22, 2024 14:38
-
-
Save oclero/9b373d0778ce702582a023aada31eb5e to your computer and use it in GitHub Desktop.
Create a std::bitset from an initializer_list<bool>
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
| // 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