我使用Python将一些文件转换为二进制格式,但遇到了一个奇怪的陷阱。在
import struct
s = struct.Struct('Bffffff')
print s.size
显然,预期的大小是25
,但它似乎将第一个字节(B
)解释为某种4字节的整数。它还将写出一个4字节的整数而不是一个字节。在
有一种解决方法,即将B
分离成一个单独的struct
,如下所示:
import struct
s1 = struct.Struct('B')
s2 = struct.Struct('ffffff')
print s1.size + s2.size
25
这种行为有什么解释吗?在
除非为字节顺序、对齐方式指定任何字符,
struct
请使用本机字节顺序对齐(@
);这会导致填充。在通过显式指定字节顺序,可以获得所需的内容:
从docs
如果你测试
所以当你添加它是},所以它将被填充成{},因此答案是{}
考虑这个例子
^{pr2}$25
。。。但另一方面,B
是1,其余的是{这里的}是{},所以最后得到了{},这与预期一致。在
B
是1
,加了3
,而{如前所述,here要重写它,必须使用非本机方法
相关问题 更多 >
编程相关推荐