我有一个基于套接字的服务器 - 客户端通信通道。我将3个整数值打包到byte []并将其写入套接字OutputStream,但我如何将其转换回来?
代码:
ByteBuffer b = ByteBuffer.allocate(12);
b.putInt(BTActions.READY_FOR_GAME);
b.putInt(i);
b.putInt(l);
try
{
mAcceptThread.getWriteSocket().write(b.array());
}
catch (IOException e)
{
e.printStackTrace();
}
答案 0 :(得分:0)
如果使用ByteBuffer
,则此缓冲区具有字节顺序;这个顺序默认是大端。
你分配一个12字节的缓冲区并写入3个int;那是12个字节,到目前为止还不错。
鉴于您没有为ByteBuffer定义订单,默认为big endian。而big endian是默认情况下JVM用于所有基本类型的内容。
因此,在向缓冲区写入3个整数后,您可以将它们读回:
final int i1, i2, i3;
buffer.rewind();
i1 = buffer.getInt();
i2 = buffer.getInt();
i3 = buffer.getInt();