Python struct.Struct.size 返回意外值 [英] Python struct.Struct.size returning unexpected value

查看:39
本文介绍了Python struct.Struct.size 返回意外值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 将一些文件转换为二进制格式,但我遇到了一个奇怪的圈套.

问题

代码

导入结构s = struct.Struct('Bffffff')打印尺寸

结果

28

显然预期的大小是 25,但它似乎将第一个字节 (B) 解释为某种 4 字节整数.它还会写出一个 4 字节的整数而不是一个字节.

变通办法

存在一种变通方法,即将 B 分离到一个单独的 struct 中,如下所示:

代码

导入结构s1 = struct.Struct('B')s2 = struct.Struct('ffffff')打印 s1.size + s2.size

结果

25

对这种行为有什么解释吗?

解决方案

除非你为字节顺序指定任何字符,对齐,struct 使用原生字节顺序,对齐(@);导致填充.

通过明确指定字节顺序,你可以得到你想要的:

<预><代码>>>>struct.Struct('!Bffffff').size # 网络字节序25>>>struct.Struct('=Bffffff').size # 原生字节顺序,无对齐.25>>>struct.Struct('>Bffffff').size # 大端25>>>struct.Struct('<Bffffff').size # 小端25>>>struct.Struct('@Bffffff').size # 本机字节顺序,对齐.(+ 原生尺寸)28

I am using Python to convert some files to a binary format, but I've run into an odd snare.

Problem

Code

import struct
s = struct.Struct('Bffffff')
print s.size

Result

28

Obviously the expected size would be 25, but it appears to be interpreting the first byte (B) as a 4-byte integer of some kind. It will also write out a 4-byte integer instead of a byte.

Work-around

A work-around exists, namely separating the B out into a separate struct, like so:

Code

import struct
s1 = struct.Struct('B')
s2 = struct.Struct('ffffff')
print s1.size + s2.size

Result

25

Is there any explanation for this behavior?

解决方案

Unless you specify any character for byte order, alignment, struct use native byte order, alignment(@); which cause padding.

By explicitly specifying byte order, you can get what you want:

>>> struct.Struct('!Bffffff').size  # network byte order
25
>>> struct.Struct('=Bffffff').size  # native byte order, no alignment.
25
>>> struct.Struct('>Bffffff').size  # big endian
25
>>> struct.Struct('<Bffffff').size  # little endian
25
>>> struct.Struct('@Bffffff').size  # native byte order, alignment. (+ native size)
28

这篇关于Python struct.Struct.size 返回意外值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆