cylus
cylus

Reputation: 377

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 trying to send data over the network, and want to ensure I know what it looks like. In python, I would use struct.pack. For example:

data = struct.pack('i', 10) 
data += "Some string"
data += struct.pack('i', 500)
print(data)

That would print the packed portions in byte order with the string in plaintext in the middle.

I tried to replicate that with ByteBuffer:

String somestring = "Some string";
ByteBuffer buffer = ByteBuffer.allocate(100);
buffer.putInt(10);
buffer.put(somestring.getbytes());
buffer.putInt(500);
System.out.println(buffer.array());

What part am I not understanding?

Upvotes: 0

Views: 2879

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533720

That sounds more complicated than you really need.

I suggest using DataOutputStream and BufferedOutputStream:

DataOutputStream dos = new DataOutputStream(
                       new BufferedOutputStream(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.

Upvotes: 1

Igor Maznitsa
Igor Maznitsa

Reputation: 873

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();

Upvotes: 0

Related Questions