[Python 实战] - No.11 Python Struct 模块使用

Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换

函数returnexplain
pack(fmt,v1,v2…)string按照给定的格式(fmt),把数据转换成字符串(字节流),并将该字符串返回.
pack_into(fmt,buffer,offset,v1,v2…)None按照给定的格式(fmt),将数据转换成字符串(字节流),并将字节流写入以offset开始的buffer中.(buffer为可写的缓冲区,可用array模块)
unpack(fmt,v1,v2…..)tuple按照给定的格式(fmt)解析字节流,并返回解析结果
pack_from(fmt,buffer,offset)tuple按照给定的格式(fmt)解析以offset开始的缓冲区,并返回解析结果
calcsize(fmt)size of fmt计算给定的格式(fmt)占用多少字节的内存,注意对齐方式

比较重要的是pack()unpack()两个函数,上表中的format格式如下:

CharacterByte orderSizeAlignment
@nativenativenative
=nativestandardnone
<little-endianstandardnone
>big-endianstandardnone
!network (= big-endian)standardnone
FormatC TypePython typeStandard sizeNotes
xpad byteno value
ccharstring of length 11
bsigned charinteger1
Bunsigned charinteger1
?_Boolbool1
hshortinteger2
Hunsigned shortinteger2
iintinteger4
Iunsigned intinteger4
llonginteger4
Lunsigned longinteger4
qlong longinteger8q和Q只适用于64位机器;
Qunsigned long longinteger8q和Q只适用于64位机器;
ffloatfloat4
ddoublefloat8
schar[]string
pchar[]string
Pvoid *integer

每个格式前可以有一个数字,表示这个类型的个数,如s格式表示一定长度的字符串,4i表示四个int

structpack函数把任意数据类型变成bytes

import struct
print(struct.pack("<i",123456))
print(struct.pack("<3s",b'hello'))
print(struct.pack("<5sl",b'hello',123456))
b'@\xe2\x01\x00'
b'hel'
b'hello@\xe2\x01\x00'

unpackbytes变成相应的数据类型:

import struct
mybytes = struct.pack("<5sl",b'hello',123456)
mystr = struct.unpack("<5sl",mybytes)
print(mystr)
(b'hello', 123456)

mybytes 字节流中有两个部分,一个是长度为5的string类型,一个是4个bytelong

如果想查看给定的格式占多少个字节,可以使用calcsize(fmt),用法如下:

print 'l:',calcsize('l')
print '@i:',calcsize('@i')
print '=i:',calcsize('=i')
print '>s:',calcsize('>s')
print '<q:',calcsize('<q')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值