Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Convert byte to integer

Tags:

java

I need to convert 2 byte array ( byte[2] ) to integer value in java. How can I do that?

like image 726
keshav Avatar asked Dec 20 '10 18:12

keshav


People also ask

Can you convert byte to int in Java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

Can you convert a byte to an int?

Byte Array to int and long. Now, let's use the BigInteger class to convert a byte array to an int value: int value = new BigInteger(bytes). intValue();

How do you convert bytes to long in Java?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();

Can we add int and byte in Java?

The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).


2 Answers

You can use ByteBuffer for this:

ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);  // if you want little-endian
int result = buffer.getShort();

See also Convert 4 bytes to int.

like image 65
Matt Ball Avatar answered Sep 19 '22 15:09

Matt Ball


In Java, Bytes are signed, which means a byte's value can be negative, and when that happens, @MattBall's original solution won't work.

For example, if the binary form of the bytes array are like this:

1000 1101 1000 1101

then myArray[0] is 1000 1101 and myArray[1] is 1000 1101, the decimal value of byte 1000 1101 is -115 instead of 141(= 2^7 + 2^3 + 2^2 + 2^0)

if we use

int result = (myArray[0] << 8) + myArray[1]

the value would be -16191 which is WRONG.

The reason why its wrong is that when we interpret a 2-byte array into integer, all the bytes are unsigned, so when translating, we should map the signed bytes to unsigned integer:

((myArray[0] & 0xff) << 8) + (myArray[1] & 0xff)

the result is 36237, use a calculator or ByteBuffer to check if its correct(I have done it, and yes, it's correct).

like image 27
DiveInto Avatar answered Sep 19 '22 15:09

DiveInto