수색…


통사론

  • 팩 (fmt, v1, v2, ...)
  • 언팩 (fmt, 버퍼)

값 목록을 바이트 객체로 형식화합니다.

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 "는 파이썬 객체를 연속적인 바이트 청크로 묶거나 파이썬 구조에 바이트 덩어리를 쪼개는 기능을 제공합니다.

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)

산출:

네이티브 byteorder : 작은 바이트 청크 : '\ 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