struct简介
使用struct可以在python数值和C的结构之间进行转换,表示方式为Python strings. 一般用于处理文件中的二进制数据(如:BMP图片)或是网络连接中的报文(如:OSPF, EIGRP报文内容)
方法:
struct.pack(fmt, v1, v2, ...)
根据fmt规定的格式对v1, v2, ...内容进行打包, 并返回打包(转换)后的字节码.
struct.pack_into(fmt, buffer, offset, v1, v2, ...)
根据fmt规定的格式对v1, v2, ...内容进行打包, 然后将打包后的内容写入buffer中offset位置.
struct.unpack(fmt, string)
根据fmt规定的格式对string(其实是字节码)进行unpack(解码), 并以元组的形式返回解码内容.
struct.unpack_from(fmt, buffer[, offset=0])
对buffer中offset位置起始的内容根据fmt进行解码,并将结果以元组形式返回.
struct.calcsize(fmt)
返回fmt指定的格式转换后的数据长度(unit: Byte)
格式参数: 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)