Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Convert bytes from stream (with offset) to integer

Tags:

java

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!

like image 677
Karloss Avatar asked Sep 12 '26 05:09

Karloss


1 Answers

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);
}
like image 115
Andremoniy Avatar answered Sep 13 '26 18:09

Andremoniy