Java 中的字节数据包解析



我遇到了问题,并试图在网上找到解决方案,但无法获得确切或类似的解决方案。我在套接字上获取数据包的问题(当然,会被读取为 byte[]),现在我想解析这个数据包。最初的两个字节是整数(类型),接下来的两个字节又是整数(有效载荷长度),然后32字节的有效载荷数据和接下来的4字节是CRC。这里的问题是我无法获得正确的方法来解析数据包,以便我得到类型,有效载荷长度。如果我知道将字节读取为正确格式的方法,我也可以读取有效载荷数据。所以任何人都可以建议如何将 byte[] 读成正确的类型。提前谢谢。

负载分组数据格式(部分) -

镜头类型

2B 无符号短
2B 无符号短
2B 无符号短
2B 无符号短
2B 无符号短
4B 签名长
4B 签名长
4B 签名长
4B 签名长

如果字节顺序是大端序并且没有填充,则可以使用 DataInputStream 的基元读取方法: readShort()为类型; 另一个readShort()用于长度; 有效载荷readFully();以及为《儿童权利公约》readInt()

您可以使用类似于DataInputStream的ByteBuffer。它还允许指定字节顺序:

// if you do not use NIO to read from socket, wrap a byte array:
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.order(ByteOrder.BIG_ENDIAN);
short short1 = bb.getShort();
short short2 = bb.getShort();
long long1 = bb.getLong();
您可以使用

DataInputStream .但是,在使用每种方法时,应仔细检查每种方法。在 Java 中,整数为 4 个字节,short 为 2。因此,当您说将 2 个字节读取为整数时,该方法将readShort()然后您可以将其转换为整数。

byte [] buffer = new byte[1024];
// populate your buffer
// you could also remove ByteArrayInputStream with the actual input stream.
DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer));
int theInteger = (int)in.readShort(); // reads 2 bytes from the stream and 
                                      // converts them to an integer

最新更新