尝试解析数据包:是否存在类似于Python的“unpack”的Java?

时间:2011-11-10 18:57:31

标签: java python

Java中有这个Python函数的等效函数吗?

struct.unpack(fmt, string)

我正在尝试将用Python编写的解析器移植到Java中,我正在寻找一种方法来实现以下代码:

handle, msgVer, source, startTime, dataFormat, sampleCount, sampleInterval, physDim,  digMin, digMax, physMin,  physMax,  freq, = unpack(self.headerFormat,self.unprocessed[pos:pos+calcsize(self.headerFormat)])

我在项目的上下文中使用它,我从网络接收字节,需要提取字节的特定部分来显示它们。

[编辑2]

我作为更新发布的结论是错误的。我删除了它以避免误导他人。

1 个答案:

答案 0 :(得分:3)

我不知道任何与Python在Java中解包的真正等价物。

传统方法是使用DataInputStream从流中读取数据(源自套接字,或者从套接字读取的字节数组,通过ByteArrayInputStream)。该类有一组读取各种原语的方法。

在你的情况下,你会做类似的事情:

DataInputStream in;
char[] handle = new char[6]; in.readFully(handle);
byte messageVersion = in.readByte();
byte source = in.readByte();
int startTime = in.readInt();
byte dataFormat = in.readByte();
byte sampleCount = in.readByte();
int sampleInterval = in.readInt();
short physDim = in.readShort();
int digMin = in.readInt();
int digMax = in.readInt();
float physMin = in.readFloat();
float physMax = in.readFloat();
int freq = in.readInt();

然后将这些变量转换为合适的对象。

请注意,我选择将每个字段打包成最小的原语来保存它;这意味着将无符号值放入相同大小的签名类型中。您可能更喜欢将它们放在更大的类型中,以便它们保持符号(例如将无符号的short放入int中); DataInputStream有一组readUnsignedXXX()方法,您可以使用它们。