python處理二進位制資料
阿新 • • 發佈:2019-01-05
struct
處理二進位制資料離不開python的struct模組,struct理解上你可以把它理解為c語言的結構體,使用該模組的pack和unpack方法,可以很容易的把二進位制資料轉換為常用的型別資料,如整型、字元型等
結構體如下:
struct Header
{
unsigned short id;
char[4] tag;
unsigned int version;
unsigned int count;
}
unpack
將二進位制資料流解析為常用的資料型別,例如:
python
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 |