我有来自socket的getInputStream()方法获得的字节流。如何从偏移 n 的流中读取1或2个字节,并将它们转换为整数。 谢谢!
答案 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);
}