Java equivalent of Python's struct.pack?

thiruvadi picture thiruvadi · Jul 9, 2010 · Viewed 10.5k times · Source

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)

Answer

SimonC picture SimonC · Jul 9, 2010

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