我在二进制文件中获取数据时遇到了这个问题。
# Write data
f = open(path, 'wb')
start_date = [2014, 1, 1, 0, 0, 0, 0]
end_date = [2014, 2, 1, 0, 0, 0, 0]
for x in range(10):
f.write(struct.pack('B', 0))
f.write(struct.pack('I', x))
f.write(struct.pack('HBBBBBH', *start_date_binary))
f.write(struct.pack('HBBBBBH', *end_date_binary))
f.close()
# Read data
f = open(path, 'rb')
for x in range(10):
data_structure = struct.unpack_from("BIHBBBBBHHBBBBBH",
f.read(FILE_INDEX_STRUCTURE))
print(data_structure)
f.close()输出是
(0, 0, 2014, 1, 1, 0, 0, 0, 0, 56832, 7, 2, 1, 0, 0, 0)
(0, 17292800, 1, 0, 0, 0, 0, 0, 2014, 258, 0, 0, 0, 0, 0, 0)
(7, 257, 0, 0, 0, 222, 7, 2, 1, 0, 0, 0, 0, 0, 3, 0)
(0, 0, 56832, 7, 2, 1, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2014)
(0, 131989504, 258, 0, 0, 0, 0, 0, 0, 5, 0, 0, 222, 7, 1, 1)
(222, 66055, 0, 0, 0, 0, 0, 6, 0, 56832, 7, 1, 1, 0, 0, 0)
(1, 0, 0, 0, 7, 0, 0, 0, 2014, 257, 0, 0, 0, 0, 0, 56832)
(0, 0, 8, 0, 0, 222, 7, 1, 1, 0, 0, 0, 0, 222, 7, 258)
(0, 2304, 56832, 7, 1, 1, 0, 0, 0, 0, 222, 7, 2, 1, 0, 0) 预期产出是
(0, 0, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 1, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 2, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 3, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 4, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 5, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 6, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 7, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 8, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)
(0, 9, 2014, 1, 1, 0, 0, 0, 0, 2014, 2, 1, 0, 0, 0, 0)编辑
获取项的结构类型,其中'B'为1,'H'为2。使用相同的unpack函数中的这些类型,类型被混淆,例如,'BH'为3,但返回4。
>>> struct.unpack_from("B", '')
...
struct.error: unpack_from requires a buffer of at least 1 bytes
>>> struct.unpack_from("H", '')
...
struct.error: unpack_from requires a buffer of at least 2 bytes
>>> struct.unpack_from("BH", '')
...
struct.error: unpack_from requires a buffer of at least 4 bytes发布于 2014-02-20 14:59:32
你遇到了填充物问题。正如docs所说:
填充只能在连续结构成员之间自动添加。在编码结构的开头或结尾不添加填充。
看看发生了什么:
>>> struct.pack("B", 0)
'\x00'
>>> struct.pack("I", 1)
'\x01\x00\x00\x00'
>>> struct.pack("BI", 0, 1)
'\x00\x00\x00\x00\x01\x00\x00\x00'所以你不能把物品分开打包,然后把它们拆在一起,除非你自己加垫子.
>>> struct.pack("B0I", 0)
'\x00\x00\x00\x00'或完全关闭垫子:
>>> struct.pack("=BI", 0, 1)
'\x00\x01\x00\x00\x00'https://stackoverflow.com/questions/21911330
复制相似问题