def pack(fmt, *args): # known case of _struct.pack
"""
pack(format, v1, v2, ...) -> bytes
Return a bytes object containing the values v1, v2, ... packed according
to the format string. See help(struct) for more on format strings.
"""
return b""
- python中只定义了六种基本类型:字符串,整数,浮点数,元组,列表,字典。并没有bytes,bytes
当Python需要通过网络与其他的平台进行交互的时候,必须考虑到将这些数据类型与其他平台或语言之间的类型进行互相转换问题。
打个比方:C++写的客户端发送一个int型(4字节)变量的数据到Python写的服务器,Python接收到表示这个整数的4个字节数据,怎么解析成Python认识的整数呢?
Python的标准模块struct就用来解决这个问题。
a=20
b=17
bytes=struct.pack("ii",a,b)
print(bytes)
b'\x14\x00\x00\x00\x11\x00\x00\x00'
print(len(bytes))
8
a,b=struct.unpack("ii",bytes)
a,b
Out[27]: (20, 17)
格式符”i”表示转换为int,进行转换后的结果长度为8个字节(int类型占用4个字节),其中十六进制的0×00000014, 0×00000011分别表示20和17。
struct.unpack
def unpack(fmt, string): # known case of _struct.unpack
"""
Return a tuple containing values unpacked according to the format string.
The buffer's size in bytes must be calcsize(format).
See help(struct) for more on format strings.
"""
pass
struct.unpack做的工作刚好与struct.pack相反,用于将字节流转换成python数据类型.该函数返回一个元组。 下面是一个简单的例子:
a=b"Hello"
b=b"world"
c=20
d=0.1111
bytes=struct.pack("5s6sif",a,b,c,d)
print(struct.calcsize("5s6sif"))
20
print(bytes)
b'Helloworld!\x00\x14\x00\x00\x00f\x88\xe3='
print(len(bytes))
20
print(struct.calcsize("5s6sif"))
20