【问题标题】:Using Java's ByteBuffer to replicate Python's struct.pack使用 Java 的 ByteBuffer 复制 Python 的 struct.pack
【发布时间】:2013-08-20 16:47:44
【问题描述】:

首先,我看到Java equivalent of Python's struct.pack?...这是一个澄清。

我是 Java 新手,并试图反映我在 Python 中使用的一些技术。我正在尝试通过网络发送数据,并希望确保我知道它的样子。在 python 中,我会使用 struct.pack。例如:

data = struct.pack('i', 10) 
data += "Some string"
data += struct.pack('i', 500)
print(data)

这将以字节顺序打印打包部分,中间是纯文本字符串。

我试图用 ByteBuffer 复制它:

String somestring = "Some string";
ByteBuffer buffer = ByteBuffer.allocate(100);
buffer.putInt(10);
buffer.put(somestring.getbytes());
buffer.putInt(500);
System.out.println(buffer.array());

我不明白哪一部分?

【问题讨论】:

    标签: java python


    【解决方案1】:

    这听起来比你真正需要的要复杂。

    我建议使用DataOutputStreamBufferedOutputStream

    DataOutputStream dos = new DataOutputStream(
                           new BufferedOutputStream(socket.getOutputStream()));
    dos.writeInt(50);
    dos.writeUTF("some string"); // this includes a 16-bit unsigned length
    dos.writeInt(500);
    

    这避免了通过直接写入流来创建比需要更多的对象。

    【讨论】:

      【解决方案2】:

      如果使用https://github.com/raydac/java-binary-block-parser,那么代码会更简单

      JBBPOut.BeginBin().Int(10).Utf8("Some string").Int(500).End().toByteArray();
      

      【讨论】:

        猜你喜欢
        • 2011-03-13
        • 1970-01-01
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 2020-09-18
        • 2014-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多