struct.error: unpack requires a string argument of length 4

前端 未结 2 1323
眼角桃花
眼角桃花 2020-12-15 17:35

Python says I need 4 bytes for a format code of \"BH\":

struct.error: unpack requires a string argument of length 4

Here is the code, I am

2条回答
  •  鱼传尺愫
    2020-12-15 18:16

    The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

    struct {                   11
        char a;      012345678901
        short b;     ------------
        char c;      axbbcxxxffffdd
        int d;
    };
    

    This structure will occupy 12 bytes of memory (x being pad bytes).

    Python works similarly (see the struct documentation):

    >>> import struct
    >>> struct.pack('BHBL',1,2,3,4)
    '\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
    >>> struct.calcsize('BHBL')
    12
    

    Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

    >>> struct.calcsize('=BHBL')
    8
    >>> struct.pack('=BHBL',1,2,3,4)
    '\x01\x02\x00\x03\x04\x00\x00\x00'
    

    Beware of letting struct handle padding. In C, these structures:

    struct A {       struct B {
        short a;         int a;
        char b;          char b;
    };               };
    

    are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

    >>> struct.pack('LB',1,2)
    '\x01\x00\x00\x00\x02'
    >>> struct.pack('LBLB',1,2,3,4)
    '\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
    

提交回复
热议问题