struct簡(jiǎn)介
使用struct可以在python數(shù)值和C的結(jié)構(gòu)之間進(jìn)行轉(zhuǎn)換,表示方式為Python strings. 一般用于處理文件中的二進(jìn)制數(shù)據(jù)(如:BMP圖片)或是網(wǎng)絡(luò)連接中的報(bào)文(如:OSPF, EIGRP報(bào)文內(nèi)容)
方法:
struct.pack(fmt, v1, v2, ...)
根據(jù)fmt規(guī)定的格式對(duì)v1, v2, ...內(nèi)容進(jìn)行打包, 并返回打包(轉(zhuǎn)換)后的字節(jié)碼.
struct.pack_into(fmt, buffer, offset, v1, v2, ...)
根據(jù)fmt規(guī)定的格式對(duì)v1, v2, ...內(nèi)容進(jìn)行打包, 然后將打包后的內(nèi)容寫入buffer中offset位置.
struct.unpack(fmt, string)
根據(jù)fmt規(guī)定的格式對(duì)string(其實(shí)是字節(jié)碼)進(jìn)行unpack(解碼), 并以元組的形式返回解碼內(nèi)容.
struct.unpack_from(fmt, buffer[, offset=0])
對(duì)buffer中offset位置起始的內(nèi)容根據(jù)fmt進(jìn)行解碼,并將結(jié)果以元組形式返回.
struct.calcsize(fmt)
返回fmt指定的格式轉(zhuǎn)換后的數(shù)據(jù)長(zhǎng)度(unit: Byte)
格式參數(shù): fmt
Order Character
Character | Byte order | Size | Alignment |
---|---|---|---|
@ | native | native | native |
= | native | standard | none |
< | little-endian | standard | none |
> | big-endian | standard | none |
! | network(= big-endian) | standard | none |
Format Character
Format | C Type | Python Type | Standard size |
---|---|---|---|
x | pad byte | no value | |
c |
char |
string of length 1 | 1 |
b |
signed char |
integer | 1 |
B |
unsigned char |
integer | 1 |
? |
_Bool |
bool | 1 |
h |
short |
integer | 2 |
H |
unsigned short |
integer | 2 |
i |
int |
integer | 4 |
I |
unsigned int |
integer | 4 |
l |
long |
integer | 4 |
L |
unsigned long |
integer | 4 |
q |
long long |
integer | 8 |
Q |
unsigned long long |
integer | 8 |
f |
float |
float | 4 |
d |
double |
float | 8 |
s |
char[] |
string | |
p |
char[] |
string | |
P |
void * |
integer |
Examples
Construct the first part of an IP packet
import struct
#69 is Version and IHL, 0 is TOS, 1420 is Total Length
first_line = struct.pack('>BBH', 69, 0, 1420)
print(first_line)
> b'E\x00\x05\x8c'
#calculate the length of format '>BBH'
struct.calcsize('>BBH')
> 4
Unpack a string according to the format character
import struct
s1 = b'E\x00\x05\x8c'
#unpack the string s1 (s1 is Bytes) according to format '>BBH'
result = struct.unpack('>BBH', s1)
print(result)
>(69, 0, 1420)