calcsize(fmt) fmt为格式化字符串,返回格式化字符串所占字节大小
比如fmt=">5sH" calcsize(fmt) 输出7 5s2个字节,H2个字节
pack
(fmt, v1, v2, ...)
按fmt将v1,v2格式化存储并返回一个字符串
pack_into
(fmt, buffer, offset, v1, v2, ...) pack完的数据存放到buffer中偏移offset的位置,offset必须指定unpack
(fmt, string) Unpack the string containing packed C structure data, according to fmt. Requires len(string) == calcsize(fmt). unpack_from(fmt,content,offset)
按fmt中格式从context偏移offset处解析出tuple对象
Unpack the buffer, containing packed C structure data, according to fmt,
starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).
搬砖整理
fmt:来自python帮助文档
The optional first format char indicates byte order, size and alignment:
@: native order, size & alignment (default) =: native order, std. size & alignment <: little-endian, std. size & alignment >: big-endian, std. size & alignment !: same as >
import struct #---------------------------------------------------------------------- def main(): """""" fmt = ">5sH" pbuf = struct.pack(fmt,"11111",1) open("1.txt","wb").write(pbuf) readbuf=open("1.txt","rb").read() tp=struct.unpack(fmt,readbuf) for i in tp: print i if __name__ == '__main__': main()
输出: