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)
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.
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.
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With