python struct pack解析_Python struct.pack()函数用法解析

struct — Interpret bytes as packed binary data

将字节解释为压缩二进制数据

Source code: Lib/struct.py

Functions and Exceptions

struct.pack(format, v1, v2, ...)

Return a bytes object containing the values v1, v2, … packed according to the format string format. The arguments must match the values required by the format exactly.

返回一个字节对象,该对象包含根据格式字符串格式打包的值v1、v2,…。参数必须与格式要求的值完全匹配。

第一个参数是后面所有参数的格式字符串,后面的每个参数必须与格式字符串描述一致。

eg:h表示short,l表示long;'hhl'表示后面有三个参数,依次是short,short,long类型

c表示 char,bytes of length 1(长度的byte数组),i表示integer 整数;'ci'表示后面有两个个参数,依次是char,integer 类型

>>> from struct import *

>>> pack('hhl', 1, 2, 3)

>>> pack('ci', b'*', 0x12131415)

Format Strings

Format strings are the mechanism used to specify the expected layout when packing and unpacking data. They are built up fromFormat Characters, which specify the type of data being packed/unpacked. In addition, there are special characters for controlling theByte Order, Size, and Alignment.

格式字符串是用于在打包和解包数据时指定预期布局的机制。它们由格式字符组成,这些字符指定要打包/解包的数据类型。此外,还有用于控制字节顺序、大小和对齐的特殊字符。

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 Characters

Format characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Standard size’ column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of','>','!'or'='. When using native size, the size of the packed value is platform-dependent.

格式字符具有以下含义;鉴于C和python值的类型,它们之间的转换应该是显而易见的。“标准大小”列是指使用标准大小时压缩值的字节大小;也就是说,当格式字符串以“”、“!”之一开头时或'='。使用本机大小时,打包值的大小取决于平台。

Format

C Type

Python type

Standard size

Notes

x

pad byte

no value

c

char

bytes of length 1

1

b

signed char

integer

1

(1),(3)

B

unsigned char

integer

1

(3)

?

_Bool

bool

1

(1)

h

short

integer

2

(3)

H

unsigned short

integer

2

(3)

i

int

integer

4

(3)

I

unsigned int

integer

4

(3)

l

long

integer

4

(3)

L

unsigned long

integer

4

(3)

q

long long

integer

8

(2), (3)

Q

unsigned long long

integer

8

(2), (3)

n

ssize_t

integer

(4)

N

size_t

integer

(4)

e

(7)

float

2

(5)

f

float

float

4

(5)

d

double

float

8

(5)

s

char[]

bytes

p

char[]

bytes

P

void *

integer

(6)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值