Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting bytes to int in Java

Tags:

java

byte

I need to convert 2 bytes (2's complement) into an int in Java code. how do I do it?

toInt(byte hb, byte lb)
{

}
like image 873
user121196 Avatar asked Jun 23 '10 20:06

user121196


People also ask

Can we convert int to byte?

An int value can be converted into bytes by using the method int. to_bytes().

How do you convert bytes to character in Java?

If you want to encode/decode characters from bytes, use Charset , CharsetEncoder , CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset) . You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets .

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


1 Answers

return ((int)hb << 8) | ((int)lb & 0xFF);

Correct operation in all cases is left as an exercise for the student.

like image 117
Yann Ramin Avatar answered Oct 23 '22 20:10

Yann Ramin