Python结构给出不正确的长度 [英] Python struct giving incorrect length

查看:48
本文介绍了Python结构给出不正确的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 结构的几个问题.请让我知道什么是正确的.

  1. 文档提到l/的长度L 为 4,但当用 calcsize 检查时它给出了 8.

    <预><代码>>>>struct.calcsize('l')8

  2. struct 模块 calcsize 给出了错误的大小.如果计算单个元素的大小,它的总和是 90,但是当与 calcsize 一起计算时,它会给出 92.

    <预><代码>>>>struct.calcsize('8s2sIII30s32s6s')92>>>struct.calcsize('8s')8>>>struct.calcsize('2s')2>>>struct.calcsize('III')12>>>struct.calcsize('30s')30>>>struct.calcsize('32s')32>>>struct.calcsize('6s')6

解决方案

jonrsharpe 在评论中发布的详细答案.

  1. ‘Standard size’一栏是指使用标准大小时打包值的大小,以字节为单位;也就是说,当格式字符串以 '<'、'>'、'!' 之一开头时或=".使用原生大小时,打包值的大小取决于平台.

    <预><代码>>>>struct.calcsize('l')8>>>struct.calcsize('=l')4

  2. 因为填充.使用 = 不使用填充.

    <预><代码>>>>struct.calcsize('=8s2sIII30s32s6s')90

Couple of issues with python struct. Please let me know what is correct.

  1. Document mentions length of l/L as 4 but when checked with calcsize it gives 8.

    >>> struct.calcsize('l')
    8
    

  2. struct module calcsize is giving wrong size. If individual element size is calculated, it's sum is 90 but when calculated together with calcsize it gives 92.

    >>> struct.calcsize('8s2sIII30s32s6s')
    92
    
    >>> struct.calcsize('8s')
    8
    
    >>> struct.calcsize('2s')
    2
    
    >>> struct.calcsize('III')
    12
    
    >>> struct.calcsize('30s')
    30
    
    >>> struct.calcsize('32s')
    32
    
    >>> struct.calcsize('6s')
    6
    

解决方案

Elaborating answer posted by jonrsharpe in comments.

  1. The ‘Standard size’ column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of '<', '>', '!' or '='. When using native size, the size of the packed value is platform-dependent.

    >>> struct.calcsize('l')
    8
    
    >>> struct.calcsize('=l')
    4
    

  2. Because of padding. Use = to not use padding.

    >>> struct.calcsize('=8s2sIII30s32s6s')
    90
    

这篇关于Python结构给出不正确的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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