Python provides a struct module to provide conversions. Here are a few of the methods in this module.
Struct.pack ():
Struct.pack is used to convert Python values from a format character to a string (because there is no byte type in Python, you can interpret the string here as a byte stream, or an array of bytes). The function prototypes are: Struct.pack (FMT, V1, v2, ...), the parameter FMT is a format string, and the related information about the format string is described below. V1, v2, ... Represents the Python value to convert. The following example converts two integers to a string (byte stream):
The code is as follows:
>>> Import struct
>>> a=20
>>> b=400
>>> str=struct.pack (' II ', A, b) #转换成字节流, although still a string, but can be transmitted over the network
>>> print len (str) #ii represents two int
8 #可以看到长度为8个字节, which is exactly the length of two int type data
>>> Print str
#二进制是乱码
>>> print repr (str)
' \x14\x00\x00\x00\x90\x01\x00\x00 ' #其中十六进制的 0x00000014, 0x00001009 respectively 20 and 400
>>>
As a result, we are able to package it arbitrarily, such as the following packaging example, which only describes the pack
The code is as follows:
Format = "! Hh%ds "% len (data)
Buffer = Struct.pack (format,opcode,blocknumber,data)
We are going to package a data, plus some header, we know that H is unsigned short is 2 bytes, and S is char type, according to the following format character information. So this buffer is a 2 byte opcode,2 byte blocknumber, and Len Long char.
Struct.unpack ():
We then run the above example:
The code is as follows:
>>> a1,a2=struct.unpack (' II ', str)
>>> print ' A1 ', A1
A1 20
>>> print ' a2= ', A2
A2= 400
You can see that "II" is delimited by four bytes and divides the 8-byte str into integers of two int.
Struct.calcsize (): The size of the output used to calculate a particular format, which is a few bytes, such as:
The code is as follows:
>>> struct.calcsize (' hh4s ')
8
>>> struct.calcsize (' II ')
8
>>>
>>> format= '! Hh%ds '% len (' Hello python ')
>>> struct.calcsize (format)
16
>>>