Skip to content Skip to sidebar Skip to footer

Attempt At Parsing Packets: Is There A Java Equivalent To Python's "unpack"?

Is there an equivalent function to this Python function in Java? struct.unpack(fmt, string) I'm trying to port a parser written in Python to Java, and I'm looking for a way to impl

Solution 1:

I am not aware of any real equivalent to Python's unpack in Java.

The conventional approach would be to read the data from a stream (originating either from a socket, or from a byte array read from the socket, via a ByteArrayInputStream) using a DataInputStream. That class has a set of methods for reading various primitives.

In your case, you would do something like:

DataInputStream in;
char[] handle = newchar[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();

And then turn those variables into a suitable object.

Note that i've opted to pack each field into the smallest primitive which will hold it; that means putting unsigned values into signed types of the same size. You might prefer to put them in bigger types, so that they keep their sign (eg putting an unsigned short into an int); DataInputStream has a set of readUnsignedXXX() methods that you can use for that.

Post a Comment for "Attempt At Parsing Packets: Is There A Java Equivalent To Python's "unpack"?"