c++c++11bitbitset

How to reverse bits in a bitset?


For example, I have the integer

a = 10;

and it's binary representation (for a 32 bit integer) is

00000000000000000000000000001010

and reversed, it becomes

01010000000000000000000000000000

Now I've seen this code, from this topcoder article that can accomplish this

x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);

Now is there some straightforward way to achieve the same effect. Perhaps by converting our bitset into a string, and then reversing that? The constructors and method for converting bitset to a string of a bitset are so complicated I can't seem to figure out how to do this.

Here's what I tried so far

#include <bitset>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <typeinfo>
#include <string>

using namespace std;

int main() {

    const unsigned int k = 32;


    int x = 10;
    bitset<k> nf(x);

    cout << nf << endl;

    string str =
        nf.to_string<char,string::traits_type,string::allocator_type>();

    reverse(str.begin(), str.end() + str.size());

    cout << str << endl;

    return 0;
}

But I'm getting this as the output:

00000000000000000000000000001010
G;ÿJG¥±žGsÿkìöUàä˜\éä˜\é

Solution

  • This is the trivial inplace approach straight on a bitset:

    template<std::size_t N>
    void reverse(std::bitset<N> &b) {
        for(std::size_t i = 0; i < N/2; ++i) {
            bool t = b[i];
            b[i] = b[N-i-1];
            b[N-i-1] = t;
        }
    }