Java equivalent of Python's struct.pack?

自作多情 提交于 2019-11-27 03:51:01

问题


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)

回答1:


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



回答2:


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



回答3:


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




回答4:


I started development of project which is very close to Python Struct: java-binary-block-parser in JBBP it will look like

JBBPOut.BeginBin().Int(0,0).Short(21,96).Int(512).End().toByteArray();


来源:https://stackoverflow.com/questions/3209898/java-equivalent-of-pythons-struct-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!