如何将 python struct.unpack 转换为 java

how to convert python struct.unpack to java

我正在尝试找到 java 等同于 python 的

struct.unpack('hccccc',raw)

https://docs.python.org/2/library/struct.html

我怎样才能以干净的方式做到这一点?

这种操作在Java中叫做"Serialization"。 有关教程,请参阅 http://www.tutorialspoint.com/java/java_serialization.htm。由于序列化适用于字节,而不是字符,您可能希望之后对这些字节进行编码以获得可打印的字符串。

这就是我处理的方式,我不 think/know 如果这是最好的方法,但经过多次搜索我自己做了,我可能会做一个实际的 complete/clean api 这样做。 如果我这样做,我会 post 在这里

x代表忽略

c 为字符

s 表示字符串

b 表示字节

import java.nio.*;

public class struct{
    public static String[] unpack(char[] packet, byte[] raw){
        String[] result = new String[packet.length];

        int pos = 0;
        int Strindex = 0;

        for (int x = 0; x < packet.length; x++){

            char type = packet[x];
            if (type == 'x'){
                pos += 1;
                continue;
            }
            else if (type == 'c'){
                char c = (char) (raw[pos] & 0xFF);
                result[Strindex] = Character.toString(c);
                Strindex += 1;
                pos += 1;
            }
            else if (type == 'h'){
                ByteBuffer bb = ByteBuffer.allocate(2);
                bb.order(ByteOrder.LITTLE_ENDIAN);
                bb.put(raw[pos]);
                bb.put(raw[pos+1]);
                short shortVal = bb.getShort(0);
                result[Strindex] = Short.toString(shortVal);
                pos += 2;
                Strindex += 1;
            }
            else if (type == 's'){
                String s = "";

                while (raw[pos] != (byte)0x00){
                    char c = (char) (raw[pos] & 0xFF);
                    s += Character.toString(c);
                    pos += 1;
                }
                result[Strindex] = s;
                Strindex += 1;
                pos += 1;
            }
            else if (type == 'b'){
                Byte p = raw[pos];
                result[Strindex] = Integer.toString(p.intValue());
                Strindex += 1;
                pos += 1;
            }
        }
        return result;
    }
}

JBBP library 能帮上忙

byte [] data = new byte [] {1,2,3,4,5,6,7,8};
JBBPFieldStruct parsed = JBBPParser.prepare("short; ubyte [5];").parse(new ByteArrayInputStream(data));
System.out.println("short = "+parsed.findFieldForType(JBBPFieldShort.class).getAsInt());
System.out.println("array = "+Arrays.toString(parsed.findFieldForType(JBBPFieldArrayUByte.class).getArray()));

今天我在调整杂音分裂哈希函数时遇到了类似的任务。所以它可能对某人有用。 对于 struct.unpack('q', msg)[0] 你可以使用 ByteBuffer.wrap(msg.getBytes()).order(ByteOrder.LITTLE_ENDIAN).getLong(); 因为 "q" 是 'long long' 的大小为 -(1<<63) 到 (1<<63)-1 (-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807)在 C++(8 字节)中等于 'long' 在 Java(8 字节)中也有“-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807”。