struct
處理二進(jìn)制數(shù)據(jù)離不開python的struct模塊草则,struct理解上你可以把它理解為c語言的結(jié)構(gòu)體辛块,使用該模塊的pack和unpack方法牵舵,可以很容易的把二進(jìn)制數(shù)據(jù)轉(zhuǎn)換為常用的類型數(shù)據(jù)叫胁,如整型枉侧、字符型等
結(jié)構(gòu)體如下:
struct Header
{
unsigned short id;
char[4] tag;
unsigned int version;
unsigned int count;
}
unpack
將二進(jìn)制數(shù)據(jù)流解析為常用的數(shù)據(jù)類型,例如:
arsc_file = open(file, "rb") #二進(jìn)制讀取文件
data = arsc_file.read(12) #讀取12字節(jié)
table_type_2,head2,file4,package4 = struct.unpack("2H2I", data)
#將這12個字節(jié)分拆為2個unsigned short(H)和2個unsigned int(I)類型數(shù)據(jù)
pack
把常用的數(shù)據(jù)類型打包成二進(jìn)制數(shù)據(jù)肛宋,例如:
new_head2 = 2
head2 = 1
file4 = 8
new_data = struct.pack("2H2I4H", table_type_2, new_head2, file4, package4,head2,head2,head2,head2)
#把常用的類型數(shù)據(jù)轉(zhuǎn)換二進(jìn)制流州藕,參數(shù)一是二進(jìn)制流格式組成
struct里面規(guī)定的數(shù)據(jù)類型表
| Format | C Type | Python | 字節(jié)數(shù)
| ------------- |:-------------:| ----------:|
| 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|