views:

109

answers:

2

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)
A: 

Closest feature in core Java is Serialization. It converts object into byte sequence and back.

Georgy Bolyuba
CAn't believe you. Even as I dislike Java, there should be something closer to being able to do things like this than serialization: Serialization gives you no control on which actual bytes are being created - it just allows you to recreate the same object with those bytes.
jsbueno
By default it gives you no control, but you can always customize it. Hint: search for readObject/writeObject on the page I gave you a link to. If that is not enough, check out http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/io/Externalizable.html
Georgy Bolyuba
+2  A: 

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