简体   繁体   中英

Python Struct and reading values in Java

I want to export a binary format and then I read the binary in Java, But i am not able to get correct values, for example

f.write(struct.pack('<f', 21.988))

in Java I have this value: 8.962863E27

I try to send a binary and match the output to ubjson library written in java, at first I use Big-endian mark but does not work, and when I use Little-endian it works like that.

Thanks for any guides.

Edit: some part of library

public JsonValue parse(final DataInputStream din) throws IOException {
        return parse(din, din.readByte());
    }

    protected JsonValue parse(final DataInputStream din, final byte type) throws IOException {
        if (type == '[')
            return parseArray(din);
        else if (type == '{')
            return parseObject(din);
        else if (type == 'Z')
            return new JsonValue(JsonValue.ValueType.nullValue);
        else if (type == 'T')
            return new JsonValue(true);
        else if (type == 'F') 
                .....

Your Java application is using the opposite endianess; you are writing little-endian, but Java interpreted the value as big endian:

>>> struct.unpack('>f', struct.pack('<f', 21.988))
(8.962863280123082e+27,)

Write big-endian and Java will read the values correctly:

struct.pack('>f', 21.988)

If that doesn't work there are other reasons that your output is not interpreted correctly. The UBJSON specification is quite clear about endianess, it should all be encoded big-endian.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM