Skip to content Skip to sidebar Skip to footer

Using Java's Bytebuffer To Replicate Python's Struct.pack

First off, I saw Java equivalent of Python's struct.pack?... this is a clarification. I am new to Java and trying to mirror some of the techniques that I have used in Python. I am

Solution 1:

That sounds more complicated than you really need.

I suggest using DataOutputStream and BufferedOutputStream:

DataOutputStreamdos=newDataOutputStream(
                       newBufferedOutputStream(socket.getOutputStream()));
dos.writeInt(50);
dos.writeUTF("some string"); // this includes a 16-bit unsigned length
dos.writeInt(500);

This avoids creating more objects than needed by writing directly to the stream.

Solution 2:

if use https://github.com/raydac/java-binary-block-parser then the code will be much easier

JBBPOut.BeginBin().Int(10).Utf8("Some string").Int(500).End().toByteArray();

Post a Comment for "Using Java's Bytebuffer To Replicate Python's Struct.pack"