title: How to reverse bits in a bitset?
body: <p>For example, I have the integer </p>
  
  <p>a = 10;</p>
  
  <p>and it's binary representation (for a 32 bit integer) is </p>
  
  <p>00000000000000000000000000001010</p>
  
  <p>and reversed, it becomes </p>
  
  <p>01010000000000000000000000000000</p>
  
  <p>Now I've seen this code, from this <a href="https://www.topcoder.com/community/data-science/data-science-tutorials/a-bit-of-fun-fun-with-bits/" rel="noreferrer">topcoder article</a> that can accomplish this </p>
  
  <pre><code>x = ((x &amp; 0xaaaaaaaa) &gt;&gt; 1) | ((x &amp; 0x55555555) &lt;&lt; 1);
  x = ((x &amp; 0xcccccccc) &gt;&gt; 2) | ((x &amp; 0x33333333) &lt;&lt; 2);
  x = ((x &amp; 0xf0f0f0f0) &gt;&gt; 4) | ((x &amp; 0x0f0f0f0f) &lt;&lt; 4);
  x = ((x &amp; 0xff00ff00) &gt;&gt; 8) | ((x &amp; 0x00ff00ff) &lt;&lt; 8);
  x = ((x &amp; 0xffff0000) &gt;&gt; 16) | ((x &amp; 0x0000ffff) &lt;&lt; 16);
  </code></pre>
  
  <p>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. </p>
  
  <p>Here's what I tried so far</p>
  
  <pre><code>#include &lt;bitset&gt;
  #include &lt;iostream&gt;
  #include &lt;algorithm&gt;
  #include &lt;cmath&gt;
  #include &lt;vector&gt;
  #include &lt;cstdlib&gt;
  #include &lt;ctime&gt;
  #include &lt;typeinfo&gt;
  #include &lt;string&gt;
  
  using namespace std;
  
  int main() {
  
      const unsigned int k = 32;
  
  
      int x = 10;
      bitset&lt;k&gt; nf(x);
  
      cout &lt;&lt; nf &lt;&lt; endl;
  
      string str =
          nf.to_string&lt;char,string::traits_type,string::allocator_type&gt;();
  
      reverse(str.begin(), str.end() + str.size());
  
      cout &lt;&lt; str &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>But I'm getting this as the output: </p>
  
  <pre><code>00000000000000000000000000001010
  G;ÿJG¥±žGsÿkìöUàä˜\éä˜\é
  </code></pre>