Python: struct.pack 和 struct.unpack 函数学习

在网络通信当中,当我们用二进制流的形式来传递数据时,需要有一种机制,使得发送端可以将数据打包再传输,接收端收到数据后能将数据解包得到原始的结构体数据。Python的struct模块就提供了这样的机制。

 

pack 和 unpack 关于这两个函数的官方定义如下:

 

struct.pack(fmtv1v2...)

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

 

struct.unpack(fmtbuffer)

Unpack from the buffer buffer (presumably packed by pack(fmt, ...)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().

 

下面我们通过代码来看看具体如何使用:

 

# -*- coding:utf-8 -*-

import struct
import binascii

pack_str1 = struct.pack('!2H',10,100)
pack_str2 = struct.pack('2H',10,100)
print pack_str1, pack_str2 #乱码
print binascii.hexlify(pack_str1) #000a0064
print binascii.hexlify(pack_str2) #0a006400
print len(pack_str1) #4

a1,a2 = struct.unpack('!2H', pack_str1)
print a1,a2 #10 100

 

代码中的‘!2H’即format,struct.pack和struct.unpack都是按照format进行打包和解包的,10和100打包的结果分别是000a和0064,其本质是字节流,但其容器是str,且长度一共是4个字节。其中!表示按照网络的对齐方式(大端)。

注:大端指较低的有效字节存放在较高的存储器地址中,较高的有效字节存放在较低的存储器地址;小端则相反。大小端的主要区别在于字节存放的顺序,采用大端更符合人的思维逻辑,采用小端更利于计算机处理。

 

FormatC TypePython TypeStandard size
Bunsigned charinteger1
Hunsigned shortinteger2
Iunsigned intinteger4

 

待续

 

参考:https://docs.python.org/3/library/struct.html#module-struct

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值