python struct模块的使用

struct模块 bytes和其他二进制数据类型的之间的转换

使用 struct.pack()函数将任意类型转成bytes

>>> import struct
>>> s = 10247890
>>> struct.pack('>I', s)
b'\x00\x9c^\xd2'
>>> s = 20140099
>>> struct.pack('>I', s)
b'\x013PC'
>>> s = 10240099
>>> struct.pack('>I', s)
b'\x00\x9c@c'
  • '>I’的意思是:表示字节顺序是big-endian,也就是网络序,I表示4字节无符号整数

使用struct.unpack()函数把bytes变成相应的数据

>>> import struct
>>> str = b'\xf0\xf0\xf0\xf0\x80\x80'
>>> struct.unpack('>IH',str)
(4042322160, 32896)
>>> struct.unpack('>HI',str)
(61680, 4042293376)
>>> struct.unpack('>3H',str)
(61680, 61680, 32896)
>>> struct.unpack('>2H',str)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: unpack requires a buffer of 4 bytes
>>> struct.unpack('>6B',str)
(240, 240, 240, 240, 128, 128)

使用struct.unpack_from(fmt,buffer,offfset)函数把bytes变成相应的数据
按照给定的格式(fmt)解析以offset开始的缓冲区,并返回解析结果

>>> import struct
>>> str = b'\xf0\xf0\xf0\xf0\x80\x80'
>>> struct.unpack_from('>I', str, 0)
(4042322160,)
>>> struct.unpack_from('>2H', str, 0)
(61680, 61680)
>>> struct.unpack_from('>3H', str, 0)
(61680, 61680, 32896)
>>> struct.unpack_from('>I', str, 2)
(4042293376,)

在这里插入图片描述

struct.unpack_from(’>B3H’, b’\xff\xfc\x00\x04\x00\x04\xff\xfc\xff\xfc\xff\xfc’,0)
在0位置,先取一个B,然后在取3个H

>>> struct.unpack_from('>B3H', b'\xff\xfc\x00\x04\x00\x04\xff\xfc\xff\xfc\xff\xfc',0)
(255, 64512, 1024, 1279)
>>> struct.unpack('>B', b'\xff')
(255,)
>>> struct.unpack('>H', b'\xfc\x00')
(64512,)
>>> struct.unpack('>H', b'\x04\x00')
(1024,)

struct.unpack(’>BIBIBf’, b’\x00\x00\x03\x03\x04\xff\x00\x03\x03\x04\x34’+b’A#33’)

>>> struct.unpack('>BIBIBf', b'\x00\x00\x03\x03\x04\xff\x00\x03\x03\x04\x34'+b'A#33')
(0, 197380, 255, 197380, 52, 10.199999809265137)
>>> strcut.unpack('>B', b'\x00')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'strcut' is not defined
>>> struct.unpack('>B', b'\x00')
(0,)
>>> struct.unpack('>I', b'\x00\x03\x03\x04')
(197380,)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值