Python的struct模块
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 TypePythonNotesxpad byteno valueccharstring of length 1bsigned charintegerBunsigned charinteger?_Boolbool(1)hshortintegerHunsigned shortintegeriintintegerIunsigned intinteger or longllongintegerLunsigned longlongqlong longlong(2)Qunsigned long longlong(2)ffloatfloatddoublefloatschar[]stringpchar[]stringPvoid *long 说明:
[*]格式字符可以以一个数字作为前缀n,表示n个连续的该格式,例如4h表示hhhh
[*]在格式(formats)中间的空白字符将被忽略
[*]s格式的计数n代表n个字节长度的string,例如’10s’代表10-byte string
format的第一个字符可以标示为字节序、对齐方式、数据类型大小等,如下表:
CharacterByte orderSize 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
页:
[1]