Suche…


Syntax

  • pack (fmt, v1, v2, ...)
  • entpacken (fmt, puffer)

Formatieren Sie eine Liste von Werten in ein Byteobjekt

from struct import pack

print(pack('I3c', 123, b'a', b'b', b'c'))  # b'{\x00\x00\x00abc'

Entpacken Sie ein Byte-Objekt gemäß einer Formatzeichenfolge

from struct import unpack

print(unpack('I3c', b'{\x00\x00\x00abc'))  # (123, b'a', b'b', b'c')

Struktur verpacken

Das Modul " struct " bietet die Möglichkeit, Python-Objekte als zusammenhängende Byte-Blöcke zu packen oder eine Menge von Byte in Python-Strukturen zu zerlegen.

Die Pack-Funktion akzeptiert eine Formatzeichenfolge und ein oder mehrere Argumente und gibt eine Binärzeichenfolge zurück. Das sieht fast so aus, als würden Sie eine Zeichenfolge formatieren, mit der Ausnahme, dass die Ausgabe keine Zeichenfolge ist, sondern ein Teil von Bytes.

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)

Ausgabe:

Native Byte-Reihenfolge: kleiner Byte-Block: '\ x03 \ x00 \ x00 \ x00 \ x04 \ x00 \ x05' Byte-Block entpackt: (3, 4, 5) Byte-Block: '\ x03 \ x00 \ x00 \ x00 \ x04 \ x00 \ x05 \ x00 '

Sie können die Bytereihenfolge des Netzwerks für Daten verwenden, die vom Netzwerk empfangen werden, oder Packdaten, um sie an das Netzwerk zu senden.

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)

Ausgabe:

Byte-Byte-Byte-Reihenfolge: '\ x03 \ x00 \ x04 \ x00 \ x05 \ x00'

Reihenfolge der Bytes des Byte-Chunks: '\ x00 \ x03 \ x00 \ x04 \ x00 \ x05'

Sie können die Optimierung optimieren, indem Sie den Aufwand für die Zuweisung eines neuen Puffers vermeiden, indem Sie einen zuvor erstellten Puffer bereitstellen.

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)

Ausgabe:

Byte-Block: '\ x03 \ x00 \ x04 \ x00 \ x05 \ x00 \ x00 \ x00'

Byte-Block: '\ x00 \ x00 \ x03 \ x00 \ x04 \ x00 \ x05 \ x00'



Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow