您的位置:首页 > 编程语言 > Python开发

python处理二进制数据

2016-09-06 18:50 435 查看

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里面规定的数据类型表

FormatC TypePython字节数
xpad byteno value1
ccharstring of length 11
bsigned charinteger1
Bunsigned charinteger1
?_Boolbool1
hshortinteger2
Hunsigned shortinteger2
iintinteger4
Iunsigned intinteger or long4
llonginteger4
Lunsigned longlong4
qlong longlong8
Qunsigned longlong long8
ffloatfloat4
ddoublefloat8
schar[]string1
pchar[]string1
Pvoid *long
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 二进制