我有一堆二进制数据(恰好是一个视频游戏存档文件的内容),其中一部分数据包含小端和大端整数值。由于没有仔细阅读文档,我尝试使用以下方式对其进行解包...
struct.unpack(
'3sB<H<H<H<H4s<I<I32s>IbBbBbBbB12s20sBB4s',
string_data
)
当然,我得到了这个神秘的错误信息:
struct.error: bad char in struct format
问题在于,
struct.unpack
格式字符串并不希望用字节序标记来标识单个字段。实际上,这里正确的格式字符串应该是这样的:struct.unpack(
'<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s',
string_data
)
除了这会翻转第三个字段的字节序(将其解析为小端序,而我实际上想将其解析为大端序)之外,没有其他问题。
有没有简单和/或“Pythonic”的解决方案来解决我的问题?我已经想到了三种可能的解决方案,但它们都不是特别优雅。如果没有更好的想法,我可能会选择第3个:
I could extract a substring and parse it separately:
(my.f1, my.f2, ...) = struct.unpack('<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data) my.f11 = struct.unpack('>I', string_data[56:60])
I could flip the bits in the field after the fact:
(my.f1, my.f2, ...) = struct.unpack('<3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data) my.f11 = swap32(my.f11)
I could just change my downstream code to expect this field to be represented differently — it's actually a bitmask, not an arithmetic integer, so it wouldn't be too hard to flip around all the bitmasks I'm using with it; but the big-endian versions of these bitmasks are more mnemonically relevant than the little-endian versions.