Serializing binary data in Python

前端 未结 1 2061
滥情空心
滥情空心 2020-11-30 15:16

I have some binary data which is in Python in the form of an array of byte strings.

Is there a portable way to serialize this data that other languages could read?

相关标签:
1条回答
  • 2020-11-30 16:13

    If you just need the binary data in the strings and can recover the boundaries between the individual strings easily, you could just write them to a file directly, as raw strings.

    If you can't recover the string boundaries easily, JSON seems like a good option:

    a = [b"abc\xf3\x9c\xc6", b"xyz"]
    serialised = json.dumps([s.decode("latin1") for s in a])
    print [s.encode("latin1") for s in json.loads(serialised)]
    

    will print

    ['abc\xf3\x9c\xc6', 'xyz']
    

    The trick here is that arbitrary binary strings are valid latin1, so they can always be decoded to Unicode and encoded back to the original string again.

    0 讨论(0)
提交回复
热议问题