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

Python的struct模块

2011-03-01 14:34 591 查看
struct模块提供将二进制数据转换为结构化数据或相反的功能,它定义了以下函数和异常:

exception struct.error

struct.pack(fmt, v1, v2, …)

返回一个string,string由v1,v2…经过给出的格式fmt组成,参数的个数有和类型要和给出的格式一一对应

struct.pack_into(fmt, buffer, offset, v1, v2, …)

按照格式fmt将v1, v2 …打包,并从buffer的偏移量offset开始写进buffer中

struct.unpack(fmt, string)

以给定的格式fmt来将string解包,结果是个元组(tuple),即使结果只有一个值。fmt所要求的长度必须和string的长度相等

struct.unpack_from(fmt, buffer[, offset=0])

以给定的格式fmt来将buffer解包,结果是个元组

struct.calcsize(fmt)

返回给出格式对应的结构的长度

格式如下表:

C Type列指Foramt列字母所代表的打包数据

Python列指打包数据在python里面表示的类型

FormatC
Type
PythonNotes
xpad
byte
no
value
ccharstring
of length 1
bsigned
char
integer
Bunsigned
char
integer
?_Boolbool(1)
hshortinteger
Hunsigned
short
integer
iintinteger
Iunsigned
int
integer
or long
llonginteger
Lunsigned
long
long
qlong
long
long(2)
Qunsigned
long long
long(2)
ffloatfloat
ddoublefloat
schar[]string
pchar[]string
Pvoid
*
long
说明:

格式字符可以以一个数字作为前缀n,表示n个连续的该格式,例如4h表示hhhh

在格式(formats)中间的空白字符将被忽略

s格式的计数n代表n个字节长度的string,例如’10s’代表10-byte string

format的第一个字符可以标示为字节序、对齐方式、数据类型大小等,如下表:

CharacterByte
order
Size
and alignment
@nativenative
=nativestandard
<little-endianstandard
>big-endianstandard
!network
(= big-endian)
standard
如果没有第一个字符,则默认为@

native byteorder表示字节序取决于本机系统

native size and alignment表示数据类型大小和对齐方式与c编译器相关

standard size and alignment表示不进行任何对齐,short为2字节,int和long为4字节,long
long为8字节,float和 double是32bit和64bit的IEEE的浮点数,_Bool为1字节

转帖自:http://www.fengyj.net/blog/?p=487
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: