Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ – How to left/tight circular shift a bitset?

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 )
{
             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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading