title: Why, in javascript, is `2 << -1` zero instead of one?
body: <p>I came across this rather strange behaviour of the bitwise shift-left operator, and I'd like to understand it better...</p>
  
  <p>Let's say we want to build a function that receives an integer and return the associated integer power of two, i.e.:</p>
  
  <p><code>power =&gt; Math.pow(2, power)</code></p>
  
  <p>A more efficient way of doing this would be to use the shift-left bitwise operator (let's say overflows are not a problem):</p>
  
  <p><code>power =&gt; 1 &lt;&lt; power</code></p>
  
  <p>And this works fine. The strange thing is that this should work too:</p>
  
  <p><code>power =&gt; 2 &lt;&lt; (power-1)</code></p>
  
  <p>because it follows from:</p>
  
  <ul>
  <li><code>2 == 1 &lt;&lt; 1</code> <em>(bitwise encoding of 2)</em></li>
  <li><code>(a &lt;&lt; b) &lt;&lt; c == a &lt;&lt; (b + c)</code> <em>(semantics of <code>&lt;&lt;</code>)</em></li>
  </ul>
  
  <p>However this is not the case, because:</p>
  
  <p><code>2 &lt;&lt; -1 == 0</code></p>
  
  <p>So, the second law fails:</p>
  
  <p><code>0 == 2 &lt;&lt; -1 == (1 &lt;&lt; 1) &lt;&lt; -1</code> <strong>!=</strong> <code>1 &lt;&lt; (1 + -1) == 1 &lt;&lt; 0 == 1</code></p>
  
  <p>At first I thought it was some problem with shifting by negative numbers, maybe js was interpreting any shift by negative number as zero? However that's also not the case, because for instance:</p>
  
  <p><code>1 &lt;&lt; -31 == 2</code></p>
  
  <p>As expected. And more to the point:</p>
  
  <p><code>2 &lt;&lt; 31 == 2 &lt;&lt; -1 == 0</code></p>
  
  <p>So... what is going on here? Testing all values of shifts for <code>2</code>, all of them yield the expected value, except for the numbers congruent to -1 mod 32, even the positive ones, which yield zero instead of one.</p>
  
  <p>Does anyone know why this happens?</p>