javaarraysbytebytebuffersigned-integer

Convert two bytes to a signed integer in java


Question in short

Is there a way to read two bytes as a signed integer?

Details & example

Given two bytes in java, each represents an integer, we can convert them to the int value they represent together by simply:

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] & 0xff) << 8) | (byteArray[3] & 0xff); 

It works perfectly when the two bits represent positive integers. But it fails when the two integers are negative. For example when:

byteArray[2] = 0xff; // -1
byteArray[3] = 0xf9; // -7

I get:

i = 65529;

which is incorrect. It should just be -8 which is 0xf8.

I tried using ByteBuffer:

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();

Didn't work. Got the same result:

i = 65529

Those are only examples. There will be more bytes and they will be representing positive and negative integers.

Is there a way to read two bytes as a signed integer and get the correct result?

Thanks in advance.


Solution

  • Two bytes as a signed integer:

    public class MyClass {
        public static void main(String args[]) {
            byte h = (byte)0xff;
            byte l = (byte)0xf9;
    
            int i = (short) ((h << 8) | l);
            System.out.println(i);
        }
    }
    

    (I'll paste the comment I made under your question here):

    Use a short instead, because the leftmost bit of your int is 0, therefore it is a positive number. But if you use a short, then you'll get the negative value you want, because the type short only have 2 bytes, then the leftmost bit will be the leftmost 1 in 0xFF, making it a negative number.