python处理二进制字节流时,或跨平台如对标c/c++的short、long、double、结构体等类型,或处理socket数据、文件等情况,可以用struct,转换和解析函数为struct.pack()和struct.unpack()。
help(struct.pack)
Help on built-in function pack in module _struct:
pack(...)
pack(fmt, v1, v2, ...) -> bytes 按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流)。
Return a bytes object containing the values v1, v2, ... packed according
to the format string fmt. See help(struct) for more on format strings.
>>> help(struct.unpack)
Help on built-in function unpack in module _struct:
unpack(...)
unpack(fmt, buffer) -> (v1, v2, ...) 按照给定的格式(fmt)解析字节流string,返回解析出来的tuple。
Return a tuple containing values unpacked according to the format string
fmt. The buffer's size in bytes must be calcsize(fmt). See help(struct)
for more on format strings.<