Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Python's struct.pack?

Tags:

Is there any function equivalent to Python's struct.pack in Java that allows me to pack and unpack values like this?

pump_on = struct.pack("IIHHI", 0, 0, 21, 96, 512)
like image 200
thiruvadi Avatar asked Jul 09 '10 04:07

thiruvadi


People also ask

What is Python struct pack?

pack() This function packs a list of values into a String representation of the specified type. The arguments must match the values required by the format exactly.

Is there a Python struct?

The struct module in Python is used to convert native Python data types such as strings and numbers into a string of bytes and vice versa. What this means is that users can parse binary files of data stored in C structs in Python.


2 Answers

I think what you may be after is a ByteBuffer:

ByteBuffer pump_on_buf = ...
pump_on_buf.putInt(0);
pump_on_buf.putInt(0);
pump_on_buf.putShort(21);
pump_on_buf.putShort(96);
pump_on_buf.putInt(512);
byte[] pump_on = pump_on_buf.array();
like image 197
SimonC Avatar answered Sep 19 '22 19:09

SimonC


Something like this:

final ByteArrayOutputStream data = new ByteArrayOutputStream();
final DataOutputStream stream = new DataOutputStream(data);
stream.writeUTF(name);
stream.writeUTF(password);
final byte[] bytes = stream.toByteArray(); // there you go

Later, you can read that data:

final DataInputStream stream = new DataInputStream(
  new ByteArrayInputStream(bytes)
);
final String user = stream.readUTF();
final String password = stream.readUTF();
like image 42
yegor256 Avatar answered Sep 17 '22 19:09

yegor256