python - 为什么分组的struct.pack会写入错误的数据?

标签 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)

最佳答案

大概是因为,正如 struct 文档明确指出的那样:

Note By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

关于python - 为什么分组的struct.pack会写入错误的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239031/

相关文章:

python - 如何在 Python Flask 框架中运行循环任务?

python - 获取上下文 basemap 以填充地 block

python - 如何在驻留在不同路径的包上使用 mod 选项 "-m"运行 Python3?

python - Django 模板每次返回 True 时都会刺痛比较

c - 定义一个在 C 头文件中传递结构的函数

python - 如何处理 urllib2.urlopen 中的®?

Python简单HTTP服务器: change response header

python - 如何在函数内部测试函数?

无法从链表中删除第一个节点

c# - 将 C++ 结构数组编码为 C#