Python integer structure is different from actual

I am trying to read one short and long from a binary using python struct.

But

print(struct.calcsize("hl")) # o/p 16

which is wrong, there should be 2 bytes for short and 8 bytes in length. I am not sure that I am using the module structincorrectly.

When I print a value for everyone, it’s

print(struct.calcsize("h")) # o/p 2
print(struct.calcsize("l")) # o/p 8

Is there a way to get python to maintain precision on datatypes?

+4
source share
2 answers

, 16 - . , short , ( , ), long.

( ), ( struct.calcsize("=l") 4 , struct.calcsize("=hl") 6 , 10, 8 long s).

, , ctypes, ctypes.Structure _pack_, ctypes.sizeof, , :

from ctypes import Structure, c_long, c_short, sizeof

class HL(Structure):
    _pack_ = 1  # Disables padding for field alignment
    # Defines (unnamed) fields, a short followed by long
    _fields_ = [("", c_short),
               ("", c_long)]

print(sizeof(HL))

10 .

, ( , struct, ):

from ctypes import *

FMT_TO_TYPE = dict(zip("cb?hHiIlLqQnNfd",
                       (c_char, c_byte, c_bool, c_short, c_ushort, c_int, c_uint,
                        c_long, c_ulong, c_longlong, c_ulonglong, 
                        c_ssize_t, c_size_t, c_float, c_double)))

def calcsize(fmt, pack=None):
    '''Compute size of a format string with arbitrary padding (defaults to native)'''
    class _(Structure):
        if packis not None:
            _pack_ = pack
        _fields_ = [("", FMT_TO_TYPE[c]) for c in fmt]
    return sizeof(_)

, , , :

>>> calcsize("hl")     # Defaults to native "natural" alignment padding
16
>>> calcsize("hl", 1)  # pack=1 means no alignment padding between members
10
+1

doc :

C- , C; , . , C. , standard native

: = .

print(struct.calcsize("=hl"))

, :

  • , : struct.calcsize("lh"). C . 8 , , 8 .

  • , : struct.calcsize("=hq")

+1

Source: https://habr.com/ru/post/1692647/


All Articles