Struct库的使用

xiaoxiao2021-02-28  114

Struct库的使用

Struct库相关介绍   Struct库可以作为Python中序列化与反序列化的库来使用,关键在于掌握如何定义格式字符串,以此得到Python的字节对象。   Struct中常用的函数如下:   pack(fmt, v1, v2, …) —— 根据所给的fmt描述的格式将值v1,v2,…转换为一个字符串。   unpack(fmt, bytes) —— 根据所给的fmt描述的格式将bytes反向解析出来,返回一个元组。   calcsize(fmt) —— 根据所给的fmt描述的格式返回该结构的大小。   格式(fmt)的参照表如下:   

Struct库使用代码示例 (1)简单数据类型的例子

import struct if "__main__" == __name__: i = 5 f = 5.0 d1 = 5.0 d2 = 5.0 b = True s = "abc" fmt = "if2d?3s" # 1-int 1-float 2-double 1-bool 1-char[] pack_data = struct.pack(fmt, i, f, d1, d2, b, s) un_i, un_f, un_d1, un_d2, un_b, un_s = struct.unpack(fmt, pack_data) print ("Source data:", i, f, d1, d2, b, s) print ("Destination data:", un_i, un_f, un_d1, un_d2, un_b, un_s)

  上例中可以依次序列化和反序列化1个int,1个float,2个double,1个bool和1个char[]类型

(2)数组类型数组的例子

import struct import numpy as np if "__main__" == __name__: array = np.array([[1, 2, 3], [4, 5, 6]]) temp_array = array.reshape(-1) larray = temp_array.tolist() fmt = "%di"%(len(larray)) pack_data = struct.pack(fmt, *larray) unpack_data = struct.unpack(fmt, pack_data) dst_array = np.array(unpack_data) dst_array = dst_array.reshape(array.shape) print("Source Array:", array) print("Destination Array:", dst_array)

  上例则显示了如何对一个数组进行pack和unpack,由于没有办法直接对大于等于2维的数组进行pack,因此均需要将大于等于2维的数组变成1维的数组,然后进行pack,在pack的时候注意其中的语法加入了“*”,这也是保证能够对1维数组直接pack的关键。

转载请注明原文地址: https://www.6miu.com/read-69346.html

最新回复(0)