struct
处理二进制数据离不开python的struct模块,struct理解上你可以把它理解为c语言的结构体,使用该模块的pack和unpack方法,可以很容易的把二进制数据转换为常用的类型数据,如整型、字符型等
结构体如下:
struct Header
{
unsigned short id;
char[4] tag;
unsigned int version;
unsigned int count;
}
unpack
将二进制数据流解析为常用的数据类型,例如:
arsc_file = open(file, "rb") #二进制读取文件
data = arsc_file.read(12) #读取12字节
table_type_2,head2,file4,package4 = struct.unpack("2H2I", data)
#将这12个字节分拆为2个unsigned short(H)和2个unsigned int(I)类型数据
pack
把常用的数据类型打包成二进制数据,例如:
new_head2 = 2
head2 = 1
file4 = 8
new_data = struct.pack("2H2I4H", table_type_2, new_head2, file4, package4,head2,head2,head2,head2)
#把常用的类型数据转换二进制流,参数一是二进制流格式组成
struct里面规定的数据类型表
| Format | C Type | Python | 字节数
| ------------- |:-------------:| ----------:|
| x | pad byte | no value | 1
| c | char| string of length 1 | 1
|b |signed char|integer|1
|B| unsigned char| integer| 1
|?| _Bool| bool| 1
|h |short |integer |2
|H |unsigned short |integer| 2
|i |int |integer |4
|I| unsigned int| integer or long| 4
|l| long| integer| 4
|L |unsigned long |long |4
|q| long long| long |8
|Q |unsigned long |long long |8
|f |float |float |4
|d |double |float |8
|s| char[]| string |1
|p |char[] |string |1
|P |void * |long|