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) { }
An int value can be converted into bytes by using the method int. to_bytes().
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 .
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes). longValue();
return ((int)hb << 8) | ((int)lb & 0xFF);
Correct operation in all cases is left as an exercise for the student.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With