title: Need help understanding "getbits()" method in Chapter 2 of K&R C
body: <p>In chapter 2, the section on bitwise operators (section 2.9), I'm having trouble understanding how one of the sample methods works.</p>
  
  <p>Here's the method provided:</p>
  
  <pre><code>unsigned int getbits(unsigned int x, int p, int n) {
      return (x &gt;&gt; (p + 1 - n)) &amp; ~(~0 &lt;&lt; n);
  }
  </code></pre>
  
  <p>The idea is that, for the given number <em>x</em>, it will return the <em>n</em> bits starting at position <em>p</em>, counting from the right (with the farthest right bit being position 0). Given the following <code>main()</code> method:</p>
  
  <pre><code>int main(void) {
      int x = 0xF994, p = 4, n = 3;
      int z = getbits(x, p, n);
      printf("getbits(%u (%x), %d, %d) = %u (%X)\n", x, x, p, n, z, z);
  
      return 0;
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <blockquote>
    <p><code>getbits(63892 (f994), 4, 3) = 5 (5)</code></p>
  </blockquote>
  
  <p>I get portions of this, but am having trouble with the "big picture," mostly because of the bits (no pun intended) that I don't understand.</p>
  
  <p>The part I'm specifically having issues with is the complements piece: <code>~(~0 &lt;&lt; n)</code>. I think I get the first part, dealing with <em>x</em>; it's this part (and then the mask) that I'm struggling with -- and how it all comes together to actually retrieve those bits. (Which I've verified it is doing, both with code and checking my results using calc.exe -- thank God it has a binary view!)</p>
  
  <p>Any help?</p>