title: Byte Array and Int conversion in Java
body: <p>I am having some difficulty with these two functions: <code>byteArrayToInt</code> and <code>intToByteArray</code>.</p>
  
  <p>The problem is that if I use one to get to another and that result to get to the former, the results are different, as you can see from my examples below.</p>
  
  <p>I cannot find the bug in the code. Any ideas are very welcome. Thanks.</p>
  
  <pre><code>public static void main(String[] args)
  {
      int a = 123;
      byte[] aBytes = intToByteArray(a);
      int a2 = byteArrayToInt(aBytes);
  
      System.out.println(a);         // prints '123'
      System.out.println(aBytes);    // prints '[B@459189e1'
      System.out.println(a2);        // prints '2063597568
              System.out.println(intToByteArray(a2));  // prints '[B@459189e1'
  }
  
  public static int byteArrayToInt(byte[] b) 
  {
      int value = 0;
      for (int i = 0; i &lt; 4; i++) {
          int shift = (4 - 1 - i) * 8;
          value += (b[i] &amp; 0x000000FF) &lt;&lt; shift;
      }
      return value;
  }
  
  public static byte[] intToByteArray(int a)
  {
      byte[] ret = new byte[4];
      ret[0] = (byte) (a &amp; 0xFF);   
      ret[1] = (byte) ((a &gt;&gt; 8) &amp; 0xFF);   
      ret[2] = (byte) ((a &gt;&gt; 16) &amp; 0xFF);   
      ret[3] = (byte) ((a &gt;&gt; 24) &amp; 0xFF);
      return ret;
  }
  </code></pre>