サーチ…


構文

  • パック(fmt、v1、v2、...)
  • unpack(fmt、buffer)

値のリストをバイトオブジェクトにフォーマットする

from struct import pack

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

書式文字列に従ってバイトオブジェクトを展開する

from struct import unpack

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

構造体のパッキング

モジュール " struct "は、Pythonオブジェクトを連続したバイトのチャンクとしてパックしたり、バイトのチャンクをPython構造体に分解したりする機能を提供します。

pack関数は、書式文字列と1つ以上の引数を取り、2進文字列を返します。これは、出力が文字列ではなくバイトのチャンクであること以外は、文字列の書式設定と非常によく似ています。

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'



Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow