为什么分组的struct.pack写错了数据?

时间:2017-05-29 09:28:37

标签: python python-3.x struct

我只花了大约30分钟调试并仔细检查Python& C#代码,找出我的struct.pack写错了数据。当我把它分成单独的调用时,它工作正常。

这就是我之前的事情

file.write(struct.pack("fffHf", kf_time / frame_divisor, kf_in_tangent, kf_out_tangent, kf_interpolation_type, kf_value))

这就是我现在所拥有的

file.write(struct.pack("f", kf_time / frame_divisor))
file.write(struct.pack("f", kf_in_tangent))
file.write(struct.pack("f", kf_out_tangent))
file.write(struct.pack("H", kf_interpolation_type))
file.write(struct.pack("f", kf_value))

为什么第一个变体不会写出我预期的数据?与单独写这些有什么不同?

(文件以二进制模式打开,平台是64位Windows,Python 3.5)

1 个答案:

答案 0 :(得分:3)

大概是因为struct文件明确指出:

  

注意默认情况下,打包给定C结构的结果       包括填充字节以保持正确的对齐       对于涉及的C类型;类似地,进行对齐       开箱时要考虑到。选择此行为是这样的       打包结构的字节完全对应于       内存中相应C结构的布局。至       处理与平台无关的数据格式或省略隐式       填充字节,使用标准大小和对齐而不是       原始大小和对齐方式:有关详细信息,请参阅Byte Order, Size, and Alignment

相关问题