I have stream of bytes, which I got by using getInputStream() method from socket. How to read 1 or 2 bytes from this stream with offset n and convert them to integer. Thanks!
You can try to use DataInputStream which allows you to read primitive types:
DataInputStream dis = new DataInputStream(...your inputStream...);
int x = dis.readInt();
UPD: More specifically, you could use the code of readInt() method:
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
UPD-2: If you read 2-bytes array and sure, that it contains full integer number, try this:
int value = (b2[1] << 8) + (b2[0] << 0)
UPD-3: Pff, full method for doing it:
public static int read2BytesInt(InputStream in, int offset) throws IOException {
byte[] b2 = new byte[2];
in.skip(offset);
in.read(b2);
return (b2[0] << 8) + (b2[1] << 0);
}
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