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个字节。其中!表示按照网络的对齐方式(大端)。

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

Format C Type Python Type Standard size
B unsigned char integer 1
H unsigned short integer 2
I unsigned int integer 4

待续

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

猜你喜欢

转载自sharley.iteye.com/blog/2377342
今日推荐