title: What's up with this reversing bit order function?
body: <p>I'm rather ashamed to admit that I don't know as much about bits and bit manipulation as I probably should. I tried to fix that this weekend by writing some 'reverse the order of bits' and 'count the ON bits' functions. I took an example from <a href="http://www.c.happycodings.com/Miscellaneous/code28.html" rel="nofollow noreferrer">here</a> but when I implemented it as below, I found I had to be looping while &lt; 29. If I loop while &lt; 32 (as in the example) Then when I try to print the integer (using a printBits function i've written) I seem to be missing the first 3 bits. This makes no sense to me, can someone help me out?</p>
  
  <p>Thanks for everyone's help, I've added comments to show changes I've made.</p>
  
  <pre><code>int reverse(int n)
  {
      int r = 0;
      int i = 0;
      for(i = 0; i &lt; 29; i++) //Should be i &lt; 32
      {
          r = (r &lt;&lt; 1) + (n &amp; 1); //| instead of + to make it obvious I'm handling bits
          n &gt;&gt;=1;
      }
  
      return r;
  }
  </code></pre>
  
  <p>Here is my printBits function:</p>
  
  <pre><code>void printBits(int n)
  {
      int mask = 0X10000000; //unsigned int mask = 0X80000000;
      while (mask)
      {
          if (mask &amp; n)
          {
              printf("1");
          }
          else
          {
              printf("0");
          }
          mask &gt;&gt;= 1;
      }
      printf("\n");
  }
  </code></pre>
  
  <p>And a working? reverse function</p>
  
  <pre><code>int reverse2(int n)
  {
      int r = n;
      int s = sizeof(n) * 7; // int s = (sizeof(n) * 8) -1
  
      for (n &gt;&gt;= 1; n; n &gt;&gt;=1)
      {
          r &lt;&lt;=1;
          r |= n &amp; 1;
          s--;
  
  
      r &lt;&lt;= s;
      return r;
  }
  </code></pre>