Search code examples
c++operatorsc++20bit-shiftbitset

C++ - How to left/right circular shift a bitset?


Let's say I have a std::bitset<28> called left28. I'm looking to left circular shift left28.

left circular shift illustration

After doing some searching, I came across std::rotl (C++20) but it doesn't seem to play nice with bitset, so I have no idea how I'm going to pull this off.


Solution

  • You can implement a left circular shift by combining right shifts with left shifts.

    template<size_t N>
    std::bitset<N> rotl( std::bitset<N> const& bits, unsigned count )
    {
                 count %= N;  // Limit count to range [0,N)
                 return bits << count | bits >> (N - count);
    // The shifted bits ^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^^^ The wrapped bits
    }
    

    Note that unlike std::rotl, the count in this example is unsigned.

    If you would like it to be signed, like an int, write a matching rotr and have each function call the other when count is negative.