I get two java bytes as input that together symbolizes a 16-bit signed integer. I need to convert it to one single java integer (signed, of course). I have come up with a "ugly" solution, that includes converting to an int, then to a short and then back to an int. Is there a shorter and more elegant way? My code is as following:
public int convert(byte b1, byte b2){
int i1 = (int) (((b2 << 8) + (b1 & 0xFF)) & 0x0000FFFF);
short s1 = (short) i1;
int i2 = (int) s1;
return i2;
}
This seems to match your converter - not certain it is simpler but it is certainly less verbose.
public int convert2(byte b1, byte b2) {
return new BigInteger(new byte[]{b2,b1}).intValue();
}
The following is equivalent:
return (short) ((b2 << 8) | (b1 & 0xFF));
byte
has a small enough range that it is practical to test this equivalence for all possible values of b1
and b2
:
byte b1 = Byte.MIN_VALUE;
do {
byte b2 = Byte.MIN_VALUE;
do {
assertEquals(convert(b1, b2), convertEquivalent(b1, b2));
} while (b2++ != Byte.MAX_VALUE);
} while (b1++ != Byte.MAX_VALUE);
@AndTurner is probably the solution you sought.
However if a byte array or some file channel (memory mapped file), input stream is involved, one may use a ByteBuffer.
byte[] bytes = ...
ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
...
short n = buf.readShort(); // Sequential
short m = buf.readShort(354L); // Direct access
User contributions licensed under CC BY-SA 3.0