python - 为什么我在 python 中得到 4 个字节的字符?

标签 python python-2.7 struct

file1 = open("test.txt", 'wb')
file1.write(struct.pack('icic', 1, '\t', 2, '\n'))
file1.close()
print os.path.getsize("test.txt")

它给了我 13。但我认为它应该是 4 + 1 + 4 + 1 = 10 个字节。似乎它存储 1 个字节的 '\n',但存储 4 个字节的 '\t'。和想法? 谢谢!

最佳答案

要获取实际的结构大小,请使用 struct.calcsize() :

>>> import struct
>>> struct.calcsize('icic')
13

那是因为您使用的是默认对齐方式,然后应用了 C 规则:

By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).

第一个 ic 将只有 5 个字节,但如果你列出它两次,C 会将其填充为 8 个,因此下一个 ic 对将其变为 13 个。如果您使用 3 个 ic 对,您将得到 21 个,依此类推。C 填充 i 整数以与 4 字节组对齐。这data structure alignment用于提高内存性能,但在尝试将其用于不同目的时可能会出乎意料。

改为选择明确的字节顺序:

>>> struct.calcsize('>icic')
10

参见 Byte Order, Size and Alignment section .

关于python - 为什么我在 python 中得到 4 个字节的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24859868/

相关文章:

C++ 指针。如何为指针结构赋值?

c - 移动双链表中的项目范围? [C]

python - Django:如何允许可疑文件操作/复制文件

python - Python 如何处理子包?

python - 任何人都可以帮助我解决我在 Python 2.7 中不断遇到的 TypeError 问题吗?

c - 将结构传递给函数会出现 'undefined reference to' 错误

python - 如何简化将具有某些值的列添加到我的数据框中的过程?

python - 在启动时启动 python 脚本并随后加载 GUI

python - 用于混合数据类型列表的 Numpy dtype

python - 为 linux 构建可执行文件