title: Bit Reversal using bitwise
body: <p>I am trying to do bit reversal in a byte. I use the code below </p>
  
  <pre><code>static int BitReversal(int n)
  {
      int u0 = 0x55555555; // 01010101010101010101010101010101
      int u1 = 0x33333333; // 00110011001100110011001100110011
      int u2 = 0x0F0F0F0F; // 00001111000011110000111100001111
      int u3 = 0x00FF00FF; // 00000000111111110000000011111111
      int u4 = 0x0000FFFF;
      int x, y, z;
      x = n;
      y = (x &gt;&gt; 1) &amp; u0;
      z = (x &amp; u0) &lt;&lt; 1;
      x = y | z;
  
      y = (x &gt;&gt; 2) &amp; u1;
      z = (x &amp; u1) &lt;&lt; 2;
      x = y | z;
  
      y = (x &gt;&gt; 4) &amp; u2;
      z = (x &amp; u2) &lt;&lt; 4;
      x = y | z;
  
      y = (x &gt;&gt; 8) &amp; u3;
      z = (x &amp; u3) &lt;&lt; 8;
      x = y | z;
  
      y = (x &gt;&gt; 16) &amp; u4;
      z = (x &amp; u4) &lt;&lt; 16;
      x = y | z;
  
      return x;
  }
  </code></pre>
  
  <p>It can reverser the bit (on a 32-bit machine), but there is a problem,
  For example, the input is 10001111101, I want to get 10111110001, but this method would reverse the whole byte including the heading 0s. The output is 10111110001000000000000000000000.
  Is there any method to only reverse the actual number? I do not want to convert it to string and reverser, then convert again. Is there any pure math method or bit operation method?</p>
  
  <p>Best Regards,</p>