Java - 将字节从流(带偏移量)转换为整数

时间:2013-01-10 16:56:28

标签: java

我有来自socket的getInputStream()方法获得的字节流。如何从偏移 n 的流中读取1或2个字节,并将它们转换为整数。 谢谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试使用DataInputStream来阅读原始类型:

DataInputStream dis = new DataInputStream(...your inputStream...);
int x = dis.readInt();

UPD:更具体地说,您可以使用readInt()方法的来源:

    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:如果您读取2字节数组并确定它包含完整整数,请尝试:

    int value = (b2[1] << 8) + (b2[0] << 0)

<击>

UPD-3: Pff,完整的方法:

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