我有一串字节流,是通过使用socket的getInputStream()方法获得的。如何从这个流中读取1或2个偏移量为n的字节,并将它们转换为整数。 谢谢!
我有一串字节流,是通过使用socket的getInputStream()方法获得的。如何从这个流中读取1或2个偏移量为n的字节,并将它们转换为整数。 谢谢!
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);
}
System.out.println( read2BytesInt(in,8)); System.out.println( read2BytesInt(in,8));
输出结果是 96 和 -1,而不是 96 和 96 呢? - Karlossin.skip()
导致移动到您的 offset
位置,接下来再次调用它会导致移动 offset*2
个位置。附注:不幸的是,在 SocketInputStream
中,您无法返回到起始位置。 - Andremoniy