373.md

May 19, 2024 ยท View on GitHub

Info

Example

#include <bitset>
constexpr std::bitset<8> bs{0b00000001};
static_assert(bs.test(0));
static_assert(not bs.test(1));

https://godbolt.org/z/W4v1Kqcfv

Puzzle

  • Can you implement bitset reverse?
template<auto Size>
constexpr auto reverse(std::bitset<Size> bs); // TODO

static_assert(0b10000000 == reverse(std::bitset<8>{0b00000001}));
static_assert(0b10000001 == reverse(std::bitset<8>{0b10000001}));
static_assert(0b11100001 == reverse(std::bitset<8>{0b10000111}));

https://godbolt.org/z/d75sW5E9x

Solutions

template<auto Size>
constexpr auto reverse(std::bitset<Size> bs) {
  std::bitset<Size> r{};
  for (auto i = 0; i < bs.size(); ++i) {
    r[r.size()-i-1] = bs[i];
  }
  return r;
}

static_assert(0b10000000 == reverse(std::bitset<8>{0b00000001}));
static_assert(0b10000001 == reverse(std::bitset<8>{0b10000001}));
static_assert(0b11100001 == reverse(std::bitset<8>{0b10000111}));

https://godbolt.org/z/8h9PGP5o6