title: Javascript bit shift- number wraps?
body: <p>I am converting some Java code to Javascript to run on node.js, and I ran into something peculiar with bit shifting.</p>
  
  <p>The original Java used a long and logical bit shifting, so I've replicated that in Javascript (I get the same results with an arithmetic shift):</p>
  
  <pre><code>var num = 3382;
  
  num &gt;&gt;&gt; 0 &amp; 0xFF; // 54, as expected
  num &gt;&gt;&gt; 8 &amp; 0xFF; // 13, as expected
  num &gt;&gt;&gt; 16 &amp; 0xFF; // 0, as expected
  num &gt;&gt;&gt; 24 &amp; 0xFF; // 0, as expected
  num &gt;&gt;&gt; 32 &amp; 0xFF; // 54??
  num &gt;&gt;&gt; 40 &amp; 0xFF; // 13??
  </code></pre>
  
  <p>I get the same results on node, FF 4 and Chrome 12.</p>
  
  <p>It seems that Javascript is wrapping the bits in the integer when it runs out of bits. Javascript, AFAIK, allows up to 32-bit numbers in the background, but this shouldn't be an issue.</p>
  
  <h2>Binary Representation</h2>
  
  <p>This is what I think is happening:</p>
  
  <p>0-shift: <code>00000000000000000000110100110110</code></p>
  
  <p>8-shift: <code>00110110000000000000000000001101</code></p>
  
  <p>16-shift: <code>00001101001101100000000000000000</code></p>
  
  <p>24-shift: <code>00000000000011010011011000000000</code></p>
  
  <p>32-shift: <code>00000000000000000000110100110110</code></p>
  
  <h2>Sanity Check</h2>
  
  <p>I wrote a little test in C to make sure I wasn't going insane (note, there are compile warnings, but that's expected):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main() {
      printf("Bit shift tests:\n");
      printf("3382 &gt;&gt; 0 &amp; 0xFF: %d\n", 3382 &gt;&gt; 0 &amp; 0xFF);
      printf("3382 &gt;&gt; 8 &amp; 0xFF: %d\n", 3382 &gt;&gt; 8 &amp; 0xFF);
      printf("3382 &gt;&gt; 16 &amp; 0xFF: %d\n", 3382 &gt;&gt; 16 &amp; 0xFF);
      printf("3382 &gt;&gt; 24 &amp; 0xFF: %d\n", 3382 &gt;&gt; 24 &amp; 0xFF);
      printf("3382 &gt;&gt; 32 &amp; 0xFF: %d\n", 3382 &gt;&gt; 32 &amp; 0xFF);
      printf("3382 &gt;&gt; 48 &amp; 0xFF: %d\n", 3382 &gt;&gt; 48 &amp; 0xFF);
      printf("3382 &gt;&gt; 56 &amp; 0xFF: %d\n", 3382 &gt;&gt; 56 &amp; 0xFF);
      printf("3382 &gt;&gt; 64 &amp; 0xFF: %d\n", 3382 &gt;&gt; 64 &amp; 0xFF);
  }
  </code></pre>
  
  <h2>Note</h2>
  
  <p>I only care about 32-bit numbers. The Java code used 64 bit numbers, but the numbers represent file sizes and I won't be using big files (all under 50 megs or so).</p>
  
  <h2>Question</h2>
  
  <p>I have read the wikipedia articles about <a href="http://en.wikipedia.org/wiki/Arithmetic_shift" rel="nofollow">arithmetic</a> and <a href="http://en.wikipedia.org/wiki/Logical_shift" rel="nofollow">logical</a> <a href="http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts" rel="nofollow">bit shifts</a>, but it doesn't seem that Javascript is following the rules.</p>
  
  <p><strong>Could someone explain to me what's going on?</strong></p>