7.1. struct
Python Python bytes C C Python
struct ( Struct ) buffer (buffer Protocol) bytes bytearray bytes
7.1.1.
:
-
struct.unpack(fmt, buffer) (
pack(fmt, ...)) buffer fmtcalcsize()
-
struct.unpack_from(fmt, buffer, offset=0) buffer offset fmt offset
calcsize()
-
struct.iter_unpack(fmt, buffer) buffer fmt
calcsize()yield
3.4 .
7.1.2.
7.1.2.1.
C (native) (byte order) (alignment) ( C )
:
@ |
native | native | native |
= |
native | standard | none |
< |
standard | none | |
> |
standard | none | |
! |
(= ) | standard | none |
'@'
Intel x86 AMD64 (x86-64) Motorola 68000 PowerPC G5 ARM Intel Itanium () sys.byteorder
C sizeof
'@' '=' :
'!'
()'<' '>'
:
7.1.2.2.
(format character) ; C Python : standard '<', '>', '!', '=' native
| C | Python | |||
|---|---|---|---|---|
x |
||||
c |
char |
1 | 1 | |
b |
signed char |
1 | (1),(3) | |
B |
unsigned char |
1 | (3) | |
? |
_Bool |
(bool) | 1 | (1) |
h |
short |
2 | (3) | |
H |
unsigned short |
2 | (3) | |
i |
int |
4 | (3) | |
I |
unsigned int |
4 | (3) | |
l |
long |
4 | (3) | |
L |
unsigned long |
4 | (3) | |
q |
long long |
8 | (2), (3) | |
Q |
unsigned long
long |
8 | (2), (3) | |
n |
ssize_t |
(4) | ||
N |
size_t |
(4) | ||
e |
(7) | 2 | (5) | |
f |
float |
4 | (5) | |
d |
double |
8 | (5) | |
s |
char[] |
bytes | ||
p |
char[] |
bytes | ||
P |
void * |
(6) |
3.3 : 'n' 'N'
3.6 : 'e'
:
'?'C99_Boolchar1'q''Q'C Clong longWindows__int64-
3.2 :
__index__()3.2 'n''N'('@') native standard'f''d''e'IEEE 754 binary32 ('f') binary64 ('d') binary16('e')'P'('@')'='struct'P'IEEE 754 binary16 "" IEEE 754 standard 2008 bit 5 bit 11 bit ( 10 bit )
6.1e-056.5e+04C : unsigned short Wikipedia half-precision floating-point format
(count) '4h' 'hhhh'
; count
's' (count) '10s' 10 '10c' 10 1 null '0s' '0c' 0
('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q') x x struct.error
3.1 : 3.0 struct.error DeprecationWarning
'p' "Pascal (pascal string)" Pascal count 1 255 pack() Pascal (count-1 ) count-1 count-1 count unpack() 'p' count 255
7.1.2.3.
/:
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8
named tuple :
>>> record = b'raymond \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)
>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name=b'raymond ', serialnum=4658, school=264, gradelevel=8)
:
>>> pack('ci', b'*', 0x12131415)
b'*\x00\x00\x00\x12\x13\x14\x15'
>>> pack('ic', 0x12131415, b'*')
b'\x12\x13\x14\x15*'
>>> calcsize('ci')
8
>>> calcsize('ic')
5
'llh0l' long 4 2 :
>>> pack('llh0l', 1, 2, 3)
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
7.1.3.
struct :
-
class
struct.Struct(format) format Struct Struct
structStruct :
-
unpack_from(buffer, offset=0) unpack_from()(buffer - offsetsize)
-
iter_unpack(buffer) iter_unpack()(buffersize)3.4 .
-