Search code examples
c++boostreverseboost-dynamic-bitset

Reverse order of boost::dynamic_bitset


Is there a clean way to return the reverse ordering of a boost::dynamic_bitset object?

For example: 01001100 becomes 00110010. The simplest solution I can think of is to convert the bitset to a string, reverse the string and convert it back to a bitset, but this seems a rather slow method that nullifies the speed of bitstring operations.

Thank you in advance!


Solution

  • boost::dynamic_bitset doesn't have iterators, so a long range of comfy STL solutions like, off the top of my head, std::reverse or std::swap or their boost counterparts are not available, I reckon that a good way would be to make your own trivial reverse method:

    #include <iostream>
    #include <boost/dynamic_bitset.hpp>
    
    void reverse(boost::dynamic_bitset<> &bs)
    {
        for (size_t begin = 0, end = bs.size() - 1; begin < end; begin++, end--)
        {
            bool b = bs[end];
            bs[end] = bs[begin];
            bs[begin] = b;
        }
    }
    
    int main()
    {
        size_t size = 8;
        boost::dynamic_bitset<> bs(size, 50);
    
        std::cout << "Normal:  " << bs << std::endl;
        reverse(bs);
        std::cout << "Reverse: " << bs << std::endl;
    }
    

    Output:

    Normal:  00110010
    Reverse: 01001100
    

    Live demo