title: Convert two bytes to a signed integer in java
body: <h2>Question in short</h2>
  
  <p>Is there a way to read two bytes as a signed integer?</p>
  
  <h2>Details &amp; example</h2>
  
  <p>Given two bytes in java, each represents an integer, we can convert them to the int value they represent together by simply:</p>
  
  <pre><code>byte[] byteArray = new byte[4];
  byteArray[0] = 0x00;
  byteArray[1] = 0x00;
  byteArray[2] = .. //a byte representing an integer
  byteArray[3] = .. //a byte representing an integer
  
  int i = ((byteArray[2] &amp; 0xff) &lt;&lt; 8) | (byteArray[3] &amp; 0xff); 
  </code></pre>
  
  <p>It works perfectly when the two bits represent positive integers. But it fails when the two integers are negative. 
  For example when: </p>
  
  <pre><code>byteArray[2] = 0xff; // -1
  byteArray[3] = 0xf9; // -7
  </code></pre>
  
  <p>I get:</p>
  
  <pre><code>i = 65529;
  </code></pre>
  
  <p>which is incorrect. It should just be -8 which is 0xf8.</p>
  
  <p><strong>I tried using ByteBuffer:</strong></p>
  
  <pre><code>byte[] array = new byte[4];
  array[0] = 0x00;
  array[1] = 0x00;
  array[2] = 0xff;
  array[3] = 0xf9;
  
  ByteBuffer buffer = ByteBuffer.wrap(array);
  int i = buffer.getInt();
  </code></pre>
  
  <p>Didn't work. Got the same result: </p>
  
  <pre><code>i = 65529
  </code></pre>
  
  <p>Those are only examples. There will be more bytes and they will be representing positive and negative integers.</p>
  
  <p>Is there a way to read two bytes as a signed integer and get the correct result?</p>
  
  <p>Thanks in advance.</p>