Python struct module parsing

  • 2020-04-02 13:47:23
  • OfStack

Python provides a struct module to provide the transformation. Here are a few of the methods in this module.

      Struct. Pack () :

Struct.pack is used to convert Python values into strings based on formatting characters (since there is no Byte type in Python, you can think of strings here as Byte streams, or Byte arrays). The function prototype is struct.pack(FMT, v1, v2,...). , the parameter FMT is a format string. Information about format strings is described below. V1, v2,... Represents the python value to be converted. The following example converts two integers to a string (byte stream) :


>>> import struct
>>> a=20
>>> b=400
>>> str=struct.pack('ii',a,b)    # Convert to a byte stream, which is still a string, but can be transmitted over the network 
>>> print len(str)               #ii  Said the two int
8                                # You can see that the length is zero 8 Two bytes, exactly two bytes int Type length of data 
>>> print str
                               # Binary is garbled 
>>> print repr(str)
'x14x00x00x00x90x01x00x00'   # hexadecimal  0x00000014, 0x00001009 respectively 20 and 400
>>>

    This allows us to group packages arbitrarily, such as the following packaging example, which only covers the pack


format = "!HH%ds" % len(data)
buffer = struct.pack(format,opcode,blocknumber,data)

  So we're going to package a piece of data, and we're going to add a bunch of packets, and we're going to know that H is unsigned and short is 2 bytes, and s is char, based on the format information below. So this buffer is 2 bytes opcode, 2 bytes blocknumber, and len long char.

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201406/2014612170554637.gif? 201451217616 ">

Struct. The unpack () :

    Let's run the above example:


>>> a1,a2=struct.unpack('ii',str)
>>> print 'a1',a1
a1 20
>>> print 'a2=',a2
a2= 400

You can see that "ii" divides the 8-byte STR into two int integers bounded by four bytes.

  Struct.calcsize (): to calculate the size of the output in a particular format, in bytes, such as:


>>> struct.calcsize('HH4s')
8
>>> struct.calcsize('ii')
8
>>>
>>> format='!HH%ds' % len('hello python')
>>> struct.calcsize(format)
16
>>>


Related articles: