Python struct giving incorrect length

人盡茶涼 提交于 2020-05-16 03:08:08

问题


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
    

回答1:


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
    


来源:https://stackoverflow.com/questions/46048166/python-struct-giving-incorrect-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!