gabca
gabca

Reputation: 13

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.

Upvotes: 1

Views: 1681

Answers (2)

Smile
Smile

Reputation: 29

With 7 bits long number b = 0b1011001:

#include <iostream>
#include <bitset>

int main() {
    int b, max;

    // highest 7 bits number.
    max     = 0b1111111;
    
    b       = 0b1011001;
    // left circular shifting.
    b = b << 1;
    while (b > max) {
        b -= max;
    }
    //---------------
    
    // Shows 0110011
    std::bitset<7> o(b);
    std::cout << o << " | " << b << std::endl;
}

And the right circular shifting is a left circular shifting at some point, so it would be something like:

b = b << 7 - 1;
while (b > max) {
    b -= max;
}

Upvotes: -1

Drew Dormann
Drew Dormann

Reputation: 63765

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.

Upvotes: 2

Related Questions