python struct 模块的使用

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

参考:
https://www.jb51.net/article/68027.htm

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值