Java等效于Python的结构。pack?

时间:2022-07-12 18:17:45

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

是否有等效于Python结构的函数。包在Java中,允许我打包和打开这样的值?

pump_on = struct.pack("IIHHI", 0, 0, 21, 96, 512)

4 个解决方案

#1


8  

I think what you may be after is a ByteBuffer:

我想,你可能想要的是一个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


3  

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


1  

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

核心Java中最接近的特性是序列化。它将对象转换成字节序列并返回。

#4


1  

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

我开始开发一个非常接近Python结构的项目:JBBP中的java-二进制-block-parser。

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

#1


8  

I think what you may be after is a ByteBuffer:

我想,你可能想要的是一个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


3  

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


1  

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

核心Java中最接近的特性是序列化。它将对象转换成字节序列并返回。

#4


1  

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

我开始开发一个非常接近Python结构的项目:JBBP中的java-二进制-block-parser。

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