Python提供了一个struct模块用于打包拆包

---------------------------------------------------------------------------

该模块的主要的方法:

  struct.pack(fmt,v1,v2,.....)

    将v1,v2等参数的值进行一层包装,包装的方法由fmt指定。被包装的参数必须严格符合fmt。最后返回一个包装后的字符串。

例如:

>>>import   struct
>>>a = 20
>>>b = 200
>>>buff = struct.pack('ii',a,b)   #转换成字节流,虽然还是字符串,但是可以用于封包传输
>>>print  len(buff)
8                                                   #可以看到长度为8个字节,正好是两个int型数据的长度
>>>print buff

#二进制是乱码
>>>print repr(buff)
'\x14\x00\x00\x00\xc8\x00\x00\x00'                #其中十六进制的 0x00000014,0x000000c8分别表示20和200
>>>

  struct.unpack(fmt,string)

    解包。用pack打包,然后就可以用unpack解包了。返回一个由解包数据(string)得到的一个元组(tuple),即使仅有一个数据也会被解包成        元组。其中len(string) 必须等于 calcsize(fmt)

例如:

>>>struct.unpack('ii',buff)#接上面的例子已有打包好的数据buff

(20,200)

>>>

  struct.calcsize(fmt)

    这个就是用来计算fmt格式所描述的结构的大小。

例如:

>>>struct.calcsize('ii')

8

>>>

  struct.unpack_from(fmt,string,offset)

    这个也是用来解包,与struct.unpack(fmt,string)类似,只是从参数string的偏移offset位置开始读

  struct.pack_into(fmt,string,offset,v1,v2,.....)

    这个也是用来打包,与struct.pack(fmt,v1,v2,.....)类似,只是从参数string的偏移offset位置开始写

---------------------------------------------------------------------------

格式字符串(format string)由一个或多个格式字符(format characters)组成,对于这些格式字符的描述参照Python manual

如下:

Format C Type Python Notes
x pad byte no value  
c char string of length 1  
b signedchar integer  
B unsignedchar integer  
? _Bool bool (1)
h short integer  
H unsignedshort integer  
i int integer  
I unsignedint integer or long  
l long integer  
L unsignedlong long  
q longlong long (2)
Q unsignedlonglong long (2)
f float float  
d double float  
s char[] string  
p char[] string  
P void* long  

---------------------------------------------------------------------------

一个例子

  1. <span style="font-size:13px;">import struct
  2. # native byteorder
  3. buffer = struct.pack("ihb", 1, 2, 3)
  4. print repr(buffer)
  5. print struct.unpack("ihb", buffer)
  6. # data from a sequence, network byteorder
  7. data = [1, 2, 3]
  8. buffer = struct.pack("!ihb", *data)
  9. print repr(buffer)
  10. print struct.unpack("!ihb", buffer) </span>

Output:

'\x01\x00\x00\x00\x02\x00\x03'
(1, 2, 3)
'\x00\x00\x00\x01\x00\x02\x03'
(1, 2, 3)

首先将参数1,2,3打包,打包前1,2,3明显属于python数据类型中的integer,pack后就变成了C结构的二进制串,转成python的string类型来显示就是  '\x01\x00\x00\x00\x02\x00\x03'。由于本机是小端('little-endian',关于大端和小端的区别请参照Google),故而高位放在低地址段。i 代表C struct中的int类型,故而本机占4位,1则表示为01000000;h 代表C struct中的short类型,占2位,故表示为0200;同理b 代表C struct中的signed char类型,占1位,故而表示为03。

---------------------------------------------------------------------------

在Format string 的首位,有一个可选字符来决定大端和小端,列表如下:

Character Byte order Size and alignment
@ native native
= native standard
< little-endian standard
> big-endian standard
! network (= big-endian) standard

如果没有附加,默认为@,即使用本机的字符顺序(大端or小端),对于C结构的大小和内存中的对齐方式也是与本机相一致的(native),比如有的机器integer为2位而有的机器则为四位;有的机器内存对其位四位对齐,有的则是n位对齐(n未知,我也不知道多少)。

还有一个标准的选项,被描述为:如果使用标准的,则任何类型都无内存对齐。

下面是官方解释:

The module defines the following exception and functions:

exception struct.error

Exception raised on various occasions; argument is a string describing what is wrong.

struct.pack(fmtv1v2...)

Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

struct.pack_into(fmtbufferoffsetv1v2...)

Pack the values v1, v2, ... according to the given format, write the packed bytes into the writable buffer starting at offset. Note that the offset is a required argument.

New in version 2.5.

struct.unpack(fmtstring)

Unpack the string (presumably packed by pack(fmt, ...)) according to the given format. The result is a tuple even if it contains exactly one item. The string must contain exactly the amount of data required by the format (len(string) must equalcalcsize(fmt)).

struct.unpack_from(fmtbuffer[, offset=0])

Unpack the buffer according to the given format. The result is a tuple even if it contains exactly one item. The buffer must contain at least the amount of data required by the format (len(buffer[offset:]) must be at least calcsize(fmt)).

New in version 2.5.

struct.calcsize(fmt)

Return the size of the struct (and hence of the string) corresponding to the given format.

比如刚才的小程序的后半部分,使用的format string中首位为!,即为大端模式标准对齐方式,故而输出的为'\x00\x00\x00\x01\x00\x02\x03',其中高位自己就被放在内存的高地址位了。

实际使用范例,解析二进制byte数组:

DateTime = struct.unpack_from('I',inData,1+singleLong*i)
dateList.append(DateTime[0])
#print(DateTime)
#时间点的数据
for j in range(0,ValueNum):
dataInTimeTemp = struct.unpack_from('I',inData,5+singleLong*i+DataByteLen*j)
# if PrecisionLen>=0: #精度计算后的结果 ,可以先无视
# dataInTime = dataInTimeTemp[0] / math.pow(10,PrecisionLen) #寻找最大值
dataList.append(dataInTimeTemp[0])

Python字节流打包拆包的更多相关文章

  1. 将自己写的Python代码打包放到PyPI上

    如果是开源的Python代码,为了能够让大家更方便的使用,放到PyPI上也许是个非常不错的主意(PyPI:Python Package Index).刚开始我以为要将代码打包放到PyPI上是一件非常复 ...

  2. python进阶--打包为exe文件

    一.Python打包为EXE文件有不少方案,比较常用的有下面两种方式: 1.使用py2exe 详细介绍:http://www.cnblogs.com/jans2002/archive/2006/09/ ...

  3. 利用pyinstaller将python脚本打包发布

    之前写了一个小工具,将excel配置表转换为json.xml.lua等配置文件.最近在学习egret,正好需要转换配置文件,刚好就用上了.然而当我想把工具拷到工作目录时,就发愁了.之前我为了方便扩展, ...

  4. Python:使用Kivy将python程序打包为apk文件

    1.概述 Kivy是一套Python下的跨平台开源应用开发框架,官网,我们可以用 它来将Python程序打包为安卓的apk安装文件.以下是在windows环境中使用. 安装和配置的过程中会下载很多东西 ...

  5. 将Python程序打包为exe方法

    将Python程序打包为exe文件,需要使用到的工具是pyinstaller pyinstaller是一个多平台的Python程序打包为exe的免费工具 安装pyinstaller: 1,在Windo ...

  6. 将Python 程序打包成 .exe格式入门

    PyInstaller PyInstaller 是一个十分有用的第三方库,可以用来打包 python 应用程序,打包完的程序就可以在没有安装 Python 解释器的机器上运行了. 它能够在 Windo ...

  7. 将Python脚本打包成可执行文件

    Python是一个脚本语言,被解释器解释执行.它的发布方式: .py文件:对于开源项目或者源码没那么重要的,直接提供源码,需要使用者自行安装Python并且安装依赖的各种库.(Python官方的各种安 ...

  8. 将python代码打包成一个app/exe

    前言 打包的代码通常都需要写一个简单的界面,一般用PyQt来写.用PyQt写界面的方法请戳这里:PyQt5的安装及基本配置    PyQt5教程 python提供了几个用来打包的模块,主要有py2ap ...

  9. [转]Python依赖打包发布详细

    Python依赖打包发布详细   http://www.cnblogs.com/mywolrd/p/4756005.html 将Python脚本打包成可执行文件   Python是一个脚本语言,被解释 ...

随机推荐

  1. Eclipse SVN冲突解决

    基本原则是:每次提交前需要先和线上的对比,先把冲突解决掉,然后把线上的更新到本地,最后把本地的提交上去. 右键项目 -> Team -> 与资源库同步 在同步视图中选择Conflicts ...

  2. ajax success 和complete 的区别

    Function) success - 当请求成功时调用的函数.这个函数会得到一个参数:从服务器返回的数据(根据“dataType”进行了格式化). Function) complete - 当请求完 ...

  3. zedboard如何从PL端控制DDR读写(一)

    看了一段时间的DDR手册,感觉大体有一点了解了,想要实际上板调试,然而实验室可用的开发板不多,拿了一块zynq板看了看,DDR确实有,但是已经集成了控制器,而且控制器还放到了PS端,PL只能通过AXI ...

  4. leetcode 83

    83. Remove Duplicates from Sorted List Given a sorted linked list, delete all duplicates such that e ...

  5. Linux下切换用户

    0x01 使用命令[su username] 这种方法能切换普通用户和root用户 0x02 从普通用户切换到root用户,还可以使用命令[sudo su] 0x03 su 是switch user的 ...

  6. 020ARM家族

    1.名称:6410.2440.210.A8.ARM9.ARM11.armv7.ARMv6(v:vsersion) 芯片的名称:6410.210.2440都是属于芯片的名称,都是来自三星公司: ARM核 ...

  7. Highcharts 连续的堆积面积图

    说明:设置两个柱形图间距为0 Highcharts柱图,设置X轴各Column的间距 plotOption : {    column : {        // 设置每个柱自身的宽度        ...

  8. 比特币钱包应用breadwallet源码

    breadwallet是一款安全.可靠和便捷的比特币钱包,可使用户免于恶意软件和其他应用中常见的安全问题的骚扰,充分利用了iOS提供的安全功能,包括AES硬件加密.app沙盒和数据保护.代码签名以及k ...

  9. [转]10分钟入门python

    本原创文章属于<Linux大棚>博客,博客地址为http://roclinux.cn.文章作者为Rocrocket Wu. 为了防止某些网站的恶性转载,特在每篇文章前加入此信息,还望读者体 ...

  10. C++实现01串排序

    题目内容:将01串首先按长度排序,长度相同时,按1的个数从少到多进行排序,1的个数相同时再按ASCII码值排序. 输入描述:输入数据中含有一些01串,01串的长度不大于256个字符. 输出描述:重新排 ...