包裝結構

模組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'