title: Java bitwise operator not working as expected
body: <p>The following code attempts to store 4 longs in a byte array.  Random access is important which is why I'm not doing this with byte streams.  Why is the below code not working?  Can you think of a more efficent way to do this?</p>
  
  <pre><code>public static void storeLong(long value, byte[] buf, int offset) {
      buf[offset] = (byte) (value &amp; 0xFFL);
      buf[offset+1] = (byte) ((value &gt;&gt;&gt; 8) &amp; 0xFFL);
      buf[offset+2] = (byte) ((value &gt;&gt;&gt; 16) &amp; 0xFFL);
      buf[offset+3] = (byte) ((value &gt;&gt;&gt; 24) &amp; 0xFFL);
      buf[offset+4] = (byte) ((value &gt;&gt;&gt; 32) &amp; 0xFFL);
      buf[offset+5] = (byte) ((value &gt;&gt;&gt; 40) &amp; 0xFFL);
      buf[offset+6] = (byte) ((value &gt;&gt;&gt; 48) &amp; 0xFFL);
      buf[offset+7] = (byte) ((value &gt;&gt;&gt; 56) &amp; 0xFFL);
  }
  
  public static long retrieveLong(byte[] buf, int offset) {
      return ((long)buf[offset]) 
          + (((long)buf[offset+1])&lt;&lt;8) 
          + (((long)buf[offset+2])&lt;&lt;16) 
          + (((long)buf[offset+3])&lt;&lt;24)
          + (((long)buf[offset+4])&lt;&lt;32) 
          + (((long)buf[offset+5])&lt;&lt;40) 
          + (((long)buf[offset+6])&lt;&lt;48) 
          + (((long)buf[offset+7])&lt;&lt;56);
  }
  
  
  public static void main(String[] args) {
      byte[] buf = new byte[32];
      storeLong(-1, buf, 0);
      storeLong(1, buf, 8);
      storeLong(Long.MAX_VALUE, buf, 16);
      storeLong(Long.MIN_VALUE, buf, 24);
  
      System.out.println(-1);
      System.out.println(1);
      System.out.println(Long.MAX_VALUE);
      System.out.println(Long.MIN_VALUE);
  
      System.out.println(retrieveLong(buf, 0));
      System.out.println(retrieveLong(buf, 8));
      System.out.println(retrieveLong(buf, 16));
      System.out.println(retrieveLong(buf, 24));
  
  }
  </code></pre>
  
  <p>The output I get from the above is the following.  You can see that the first four numbers do not match the next 4:</p>
  
  <pre><code>-1
  1
  9223372036854775807
  -9223372036854775808
  
  -72340172838076673
  1
  9151031864016699135
  -9223372036854775808
  </code></pre>