struct — impacchetta e spacchetta tipi di dati primitivi¶
Questo modulo esegue conversioni tra valori Python e struct in stile C rappresentati come oggetti bytes Python, usando stringhe di formato per descrivere il layout dei dati.
Sono supportati i seguenti ordini di byte:
Carattere |
Ordine di byte |
Dimensione |
Allineamento |
|---|---|---|---|
@ |
nativo |
nativo |
nativo |
< |
little-endian |
standard |
nessuno |
> |
big-endian |
standard |
nessuno |
! |
network (= big-endian) |
standard |
nessuno |
Sono supportati i seguenti tipi di dati:
Formato |
Tipo C |
Tipo Python |
Dimensione standard |
|---|---|---|---|
b |
signed char |
integer |
1 |
B |
unsigned char |
integer |
1 |
h |
short |
integer |
2 |
H |
unsigned short |
integer |
2 |
i |
int |
integer (1) |
4 |
I |
unsigned int |
integer (1) |
4 |
l |
long |
integer (1) |
4 |
L |
unsigned long |
integer (1) |
4 |
q |
long long |
integer (1) |
8 |
Q |
unsigned long long |
integer (1) |
8 |
e |
n/d (half-float) |
float (2) |
2 |
f |
float |
float (2) |
4 |
d |
double |
float (2) |
8 |
s |
char[] |
bytes |
|
P |
void * |
integer |
Richiede il supporto long quando usato con valori più grandi di 30 bit.
Richiede il supporto in virgola mobile.
Differenza rispetto a CPython
Gli spazi bianchi non sono supportati nelle stringhe di formato.
Esempi¶
Impacchetta e spacchetta valori little-endian. Il prefisso < seleziona l’ordine di byte little-endian con dimensioni standard e senza allineamento:
import struct
# Pack an unsigned short (H, 2 bytes) then an unsigned int (I, 4 bytes).
data = struct.pack("<HI", 7, 1000)
# data == b'\x07\x00\xe8\x03\x00\x00'
# Unpack returns a tuple of the values, in order.
struct.unpack("<HI", data)
# (7, 1000)
# calcsize() reports how many bytes the format needs.
struct.calcsize("<HI")
# 6
Impacchetta in e spacchetta da un buffer esistente a un offset di byte:
buf = bytearray(8)
# Write a little-endian signed int (i) at offset 2.
struct.pack_into("<i", buf, 2, -12345)
# buf == bytearray(b'\x00\x00\xc7\xcf\xff\xff\x00\x00')
# Read it back from the same offset.
struct.unpack_from("<i", buf, 2)
# (-12345,)
Funzioni¶
- struct.calcsize(fmt: str) int¶
Restituisce il numero di byte necessari per memorizzare il fmt fornito.
- struct.pack(fmt: str, *values: Any) bytes¶
Impacchetta i values secondo la stringa di formato fmt. Il valore restituito è un oggetto bytes che codifica i valori.
- struct.pack_into(fmt: str, buffer: Any, offset: int, *values: Any) None¶
Impacchetta i values secondo la stringa di formato fmt in un buffer a partire da offset. offset può essere negativo per contare dalla fine del buffer.