title: Unwanted Java bitshift behavior
body: <p>I'm generating bitmasks for some calculations I'm doing, where I need to mask an int such that all except the x rightmost bits become zero. I do this using:</p>
  
  <pre><code>int mask = ~(-1 &lt;&lt; x);
  </code></pre>
  
  <p>This works fine for all values of x except for x = 32. It should return -1 then, but it returns 0. What is happening here?</p>
  
  <p>Also, I tried this:</p>
  
  <pre><code>int mask = -1 &gt;&gt;&gt; 32 - x;
  </code></pre>
  
  <p>At x = 0 it should return 0, yet it returns -1. Somehow shifting something by 32 causes the operation to return the left side of the operator. When I try shifting -1 by 33 or 34 bits it returns a value as if it shifted by 1 or 2. Am I correct in assuming Java actually does something like this:</p>
  
  <pre><code>int mask = ~(-1 &lt;&lt; x % 32);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>int mask = -1 &gt;&gt;&gt; (32 - x) % 32;
  </code></pre>
  
  <p>?</p>
  
  <p>If so, why would you want this loop around behavior if you go above the 32 bit length of the int? The documentation on Oracle clearly states:</p>
  
  <blockquote>
    <p>The unsigned right shift operator ">>>" shifts a zero into the
    leftmost position</p>
  </blockquote>
  
  <p>But clearly that's not actually what it's doing when it has to shift by more than 32...</p>