0

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?

Community
  • 1
  • 1
cylus
  • 357
  • 1
  • 4
  • 14

2 Answers2

1

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.

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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();
Igor Maznitsa
  • 833
  • 7
  • 12