title: java integer to byte, and byte to integer
body: <p>I am aware -that in Java- int is 4 bytes. But I wish to covert an int to n-bytes array, where n can be 1, 2, 3, or 4 bytes. I want to have it as signed byte/bytes, so that if I need to convert them back to int (event if it was 1 byte), I get the same signed int. I am fully aware about the possibility of precision loss when converting from int to 3 or lower bytes.</p>
  
  <p>I managed to convert from int to n-byte, but converting it back for a negative number yield unsigned results.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>int to bytes (parameter n specify the number of bytes required 1,2,3, or 4 regardless of possible precession loss)</p>
  
  <pre><code>public static byte[] intToBytes(int x, int n) {
      byte[] bytes = new byte[n];
      for (int i = 0; i &lt; n; i++, x &gt;&gt;&gt;= 8)
          bytes[i] = (byte) (x &amp; 0xFF);
      return bytes;
  }
  </code></pre>
  
  <p>bytes to int (regardless of how many bytes 1,2,3, or 4)</p>
  
  <pre><code>public static int bytesToInt(byte[] x) {
      int value = 0;
      for(int i = 0; i &lt; x.length; i++)
          value += ((long) x[i] &amp; 0xffL) &lt;&lt; (8 * i);
      return value;
  }
  </code></pre>
  
  <p>There is probably a problem in the bytes to int converter.</p>