包装结构
模块struct提供了将 python 对象打包为连续的字节块或将一大块字节分解为 python 结构的工具。
pack 函数接受格式字符串和一个或多个参数,并返回二进制字符串。这看起来非常类似于格式化字符串,除了输出不是字符串而是一块字节。
import struct
import sys
print "Native byteorder: ", sys.byteorder
# If no byteorder is specified, native byteorder is used
buffer = struct.pack("ihb", 3, 4, 5)
print "Byte chunk: ", repr(buffer)
print "Byte chunk unpacked: ", struct.unpack("ihb", buffer)
# Last element as unsigned short instead of unsigned char ( 2 Bytes)
buffer = struct.pack("ihh", 3, 4, 5)
print "Byte chunk: ", repr(buffer)
输出:
本机字节顺序:小字节块:’\ x03 \ x00 \ x00 \ x00 \ x04 \ x00 \ x05’字节块解压缩:(3,4,5)字节块:’\ x03 \ x00 \ x00 \ x00 \ x04 \ x00 \ X05 \ X00'
你可以使用网络字节顺序与从网络接收的数据或打包数据将其发送到网络。
import struct
# If no byteorder is specified, native byteorder is used
buffer = struct.pack("hhh", 3, 4, 5)
print "Byte chunk native byte order: ", repr(buffer)
buffer = struct.pack("!hhh", 3, 4, 5)
print "Byte chunk network byte order: ", repr(buffer)
输出:
字节块本机字节顺序:’\ x03 \ x00 \ x04 \ x00 \ x05 \ x00'
字节块网络字节顺序:’\ x00 \ x03 \ x00 \ x04 \ x00 \ x05'
你可以通过提供先前创建的缓冲区来避免分配新缓冲区的开销来进行优化。
import struct
from ctypes import create_string_buffer
bufferVar = create_string_buffer(8)
bufferVar2 = create_string_buffer(8)
# We use a buffer that has already been created
# provide format, buffer, offset and data
struct.pack_into("hhh", bufferVar, 0, 3, 4, 5)
print "Byte chunk: ", repr(bufferVar.raw)
struct.pack_into("hhh", bufferVar2, 2, 3, 4, 5)
print "Byte chunk: ", repr(bufferVar2.raw)
输出:
字节块:’\ x03 \ x00 \ x04 \ x00 \ x05 \ x00 \ x00 \ x00'
字节块:’\ x00 \ x00 \ x03 \ x00 \ x04 \ x00 \ x05 \ x00'