加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 用native字节顺序解释struct.pack中的额外填充

发布时间:2020-12-20 11:37:46 所属栏目:Python 来源:网络整理
导读:有人可以解释为什么我在使用struct.pack的本地字节顺序时会获得额外的字节数吗? import struct struct.pack('cI','a',1)'ax00x00x00x01x00x00x00' struct.pack('cI',1)'ax01x00x00x00' 所以本机字节顺序在它之前有’a’然后是3-(00字节).为什么
有人可以解释为什么我在使用struct.pack的本地字节顺序时会获得额外的字节数吗?

>>> import struct
>>> struct.pack('cI','a',1)
'ax00x00x00x01x00x00x00'

>>> struct.pack('<cI',1)
'ax01x00x00x00'

所以本机字节顺序在它之前有’a’然后是3-(00字节).为什么本地字节顺序具有这些字节而小字节序或大端字节顺序不具有?

解决方法

这在 struct module documentation中解释:

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.

在Byte Order,Alignment:

….

Native size and alignment are determined using the C compiler’s sizeof expression. This is always combined with native byte order.

Notes:

  1. Padding is only automatically added between successive structure
    members.
  2. No padding is added at the beginning or the end of the
    encoded struct. No padding is added when using non-native size and
    alignment,e.g. with ‘<’,‘>’,‘=’,and ‘!’.
  3. To align the end of a structure to the alignment requirement of a particular type,end the format with the code for that type with a repeat count of zero. See Examples.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读