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

3

我有一串字节流,是通过使用socket的getInputStream()方法获得的。如何从这个流中读取1或2个偏移量为n的字节,并将它们转换为整数。 谢谢!


1
要获取偏移量,必须先读取它们之前的所有字节。无法从套接字随机访问流。 - Peter Lawrey
1个回答

2
您可以尝试使用DataInputStream,它允许您读取原始类型:
DataInputStream dis = new DataInputStream(...your inputStream...);
int x = dis.readInt();

更新:更具体地说,您可以使用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));

更新-2: 如果您读取 2 字节数组,并确定其包含完整的整数,可以尝试这样做:


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

更新-3: 噗,完整的方法如下:

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

我还想指定要读取多少字节 - 整数为1或2个字节。 - Karloss
非常感谢,它起作用了。但是为什么如果我写 System.out.println( read2BytesInt(in,8)); System.out.println( read2BytesInt(in,8)); 输出结果是 96 和 -1,而不是 96 和 96 呢? - Karloss
由于第一个 in.skip() 导致移动到您的 offset 位置,接下来再次调用它会导致移动 offset*2 个位置。附注:不幸的是,在 SocketInputStream 中,您无法返回到起始位置。 - Andremoniy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接