Python使用struct处理二进制
来源:互联网 发布:北京的打车软件 编辑:程序博客网 时间:2024/04/28 12:24
Python模块——struct(字节流,组包拆包实现)
[日期:2014-02-24] 来源:Linux社区 作者:Linux [字体:大 中 小]
我们知道python只定义了6种数据类型,字符串,整数,浮点数,列表,元组,字典。但是C语言中有些字节型的变量,在python中该如何实现呢?这点颇为重要,特别是要在网络上进行数据传输的话。
python提供了一个struct模块来提供转换。下面就介绍这个模块中的几个方法。
struct.pack():
struct.pack用于将Python的值根据格式符,转换为字符串(因为Python中没有字节(Byte)类型,可以把这里的字符串理解为字节流,或字节数组)。其函数原型为:struct.pack(fmt, v1, v2, …),参数fmt是格式字符串,关于格式字符串的相关信息下面有所介绍。v1, v2, …表示要转换的python值。下面的例子将两个整数转换为字符串(字节流):
>>> import struct>>> a=20>>> b=400>>> str=struct.pack('ii',a,b) #转换成字节流,虽然还是字符串,但是可以在网络上传输>>> print len(str) #ii 表示两个int
8 #可以看到长度为8个字节,正好是两个int型数据的长度
>>> print str#二进制是乱码>>> print repr(str)'\x14\x00\x00\x00\x90\x01\x00\x00' #其中十六进制的 0x00000014, 0x00001009分别表示20和400>>>
由此我们就可以任意的进行组包了,比如下面一个打包的例子,只介绍其中的pack
format = "!HH%ds" % len(data)buffer = struct.pack(format,opcode,blocknumber,data)
我们要对一个数据进行打包,加上一些个包头,我们根据下面的格式符信息,知道H是unsigned short是2个字节,而s是char型。所以这个buffer就是2个字节的opcode,2个字节的blocknumber,和len长的char。
Python模块——struct(字节流,组包拆包实现)
struct.unpack():
我们接着上面的例子运行:
>>> a1,a2=struct.unpack('ii',str)>>> print 'a1',a1a1 20>>> print 'a2=',a2a2= 400
可以看到 “ii”以四个字节为分界,把8个字节的str分成了两个int型的整数。
struct.calcsize():用来计算特定格式的输出的大小,是几个字节,比如:
>>> struct.calcsize('HH4s')8>>> struct.calcsize('ii')8>>>>>> format='!HH%ds' % len('hello python')>>> struct.calcsize(format)16>>>
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- python 使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Python使用struct处理二进制
- Codeforces Round #324 (Div. 2)D. Dima and Lisa
- ios9兼容系列之解决iPad提交报错“iPad Multitasking support requires launch story board in bundle '”
- poj 3280 Cheapest Palindrome【区间DP】
- Android应用安全防御
- 数据库锁了
- Python使用struct处理二进制
- 【leetcode c++】160 Intersection of Two Linked Lists
- tcpcopy在语音识别的应用
- 2015年10月9号 从业php4个月整
- 常量指针和指向常量的指针
- 华为某年的一个机考题:计算最后一个出列者的编号
- hdoj 1142 A Walk Through the Forest
- android 实践-2015/09/09
- bootstrap-table实现两个表格之间数据的传递,表格添加行删除行功能