pack、unpack、pack_into、unpack_from

import struct

#pack - unpack  
print  
print '===== pack - unpack ====='  
  
str = struct.pack("ii", 20, 400)  
print 'str:', str  
print 'len(str):', len(str) # len(str): 8   
  
a1, a2 = struct.unpack("ii", str)  
print "a1:", a1  # a1: 20  
print "a2:", a2  # a2: 400  
  
print 'struct.calcsize:', struct.calcsize("ii") # struct.calcsize: 8  

unpack

print  
print '===== unpack ====='  
  
string = 'test astring'  
format = '5s 4x 3s'  
print struct.unpack(format, string) # ('test ', 'ing')  
  
string = 'he is not very happy'  
format = '2s 1x 2s 5x 4s 1x 5s'  
print struct.unpack(format, string) # ('he', 'is', 'very', 'happy')  

pack

print  
print '===== pack ====='  
  
a = 20  
b = 400  
  
str = struct.pack("ii", a, b)  
print 'length:', len(str) #length: 8  
print str  
print repr(str) # '/x14/x00/x00/x00/x90/x01/x00/x00'  
  

pack_into - unpack_from

print  
print '===== pack_into - unpack_from ====='  
from ctypes import create_string_buffer  
  
buf = create_string_buffer(12)  
print repr(buf.raw)  
  
struct.pack_into("iii", buf, 0, 1, 2, -1)  
print repr(buf.raw)  
  
print struct.unpack_from("iii", buf, 0)  

运行结果:
[work@db-testing-com06-vm3.db01.baidu.com Python]$ python struct_pack.py
===== pack - unpack =====str: �?len(str): 8a1: 20a2: 400struct.calcsize: 8
===== unpack =====('test ', 'ing')('he', 'is', 'very', 'happy')
===== pack =====length: 8�?'/x14/x00/x00/x00/x90/x01/x00/x00'
===== pack_into - unpack_from ====='/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00/x00''/x01/x00/x00/x00/x02/x00/x00/x00/xff/xff/xff/xff'(1, 2, -1)

pack的打印

如果直接用 print pack打印,会出来一串乱码,
需要用

print repr(pack)

==============================================================================

Python是一门非常简洁的语言,对于数据类型的表示,不像其他语言预定义了许多类型(如:在C#中,光整型就定义了8种)
它只定义了六种基本类型:字符串,整数,浮点数,元组(set),列表(array),字典(key/value)
通过这六种数据类型,我们可以完成大部分工作。但当Python需要通过网络与其他的平台进行交互的时候,必须考虑到将这些数据类型与其他平台或语言之间的类型进行互相转换问题。打个比方:C++写的客户端发送一个int型(4字节)变量的数据到Python写的服务器,Python接收到表示这个整数的4个字节数据,怎么解析成Python认识的整数呢? Python的标准模块struct就用来解决这个问题。

struct模块的内容不多,也不是太难,下面对其中最常用的方法进行介绍:

1、 struct.pack

struct.pack用于将Python的值根据格式符,转换为字符串(因为Python中没有字节(Byte)类型,可以把这里的字符串理解为字节流,或字节数组)。其函数原型为:struct.pack(fmt, v1, v2, ...),参数fmt是格式字符串,关于格式字符串的相关信息在下面有所介绍。v1, v2, ...表示要转换的python值。下面的例子将两个整数转换为字符串(字节流):

**[python]** [view plain](http://blog.csdn.net/ithomer/article/details/5974029#) [copy](http://blog.csdn.net/ithomer/article/details/5974029#)
 [print](http://blog.csdn.net/ithomer/article/details/5974029#)[?](http://blog.csdn.net/ithomer/article/details/5974029#)

#!/usr/bin/env python  
#encoding: utf8  
  
import sys  
reload(sys)  
sys.setdefaultencoding("utf-8")  
  
import struct  
  
a = 20  
b = 400   
str = struct.pack("ii", a, b)  
print 'length: ', len(str)          # length:  8  
print str                           # 乱码: �  
print repr(str)                     # '\x14\x00\x00\x00\x90\x01\x00\x00'  

格式符"i"表示转换为int,'ii'表示有两个int变量。
进行转换后的结果长度为8个字节(int类型占用4个字节,两个int为8个字节)
可以看到输出的结果是乱码,因为结果是二进制数据,所以显示为乱码。
可以使用python的内置函数repr来获取可识别的字符串,其中十六进制的0x00000014, 0x00001009分别表示20和400。

2、 struct.unpack

**struct.unpack做的工作刚好与struct.pack相反,用于将字节流转换成python数据类型。它的函数原型为:struct.unpack(fmt, string),该函数返回一个元组。
下面是一个简单的例子:


#!/usr/bin/env python  
#encoding: utf8  
  
import sys  
reload(sys)  
sys.setdefaultencoding("utf-8")  
  
import struct  
  
a = 20  
b = 400   
  
# pack  
str = struct.pack("ii", a, b)  
print 'length: ', len(str)          # length:  8  
print str                           # 乱码: �  
print repr(str)                     # '\x14\x00\x00\x00\x90\x01\x00\x00'  
  
# unpack  
str2 = struct.unpack("ii", str)  
print 'length: ', len(str2)          # length:  2  
print str2                           # (20, 400)  
print repr(str2)                     # (20, 400)  

3、 struct.calcsize

struct.calcsize用于计算格式字符串所对应的结果的长度,如:struct.calcsize('ii'),返回8。因为两个int类型所占用的长度是8个字节。

import struct  
print "len: ", struct.calcsize('i')       # len:  4  
print "len: ", struct.calcsize('ii')      # len:  8  
print "len: ", struct.calcsize('f')       # len:  4  
print "len: ", struct.calcsize('ff')      # len:  8  
print "len: ", struct.calcsize('s')       # len:  1  
print "len: ", struct.calcsize('ss')      # len:  2  
print "len: ", struct.calcsize('d')       # len:  8  
print "len: ", struct.calcsize('dd')      # len:  16  

4、 struct.pack_into、 struct.unpack_from

这两个函数在Python手册中有所介绍,但没有给出如何使用的例子。其实它们在实际应用中用的并不多。Google了很久,才找到一个例子,贴出来共享一下:

#!/usr/bin/env python  
#encoding: utf8  
  
import sys  
reload(sys)  
sys.setdefaultencoding("utf-8")  
  
import struct  
from ctypes import create_string_buffer  
  
buf = create_string_buffer(12)  
print repr(buf.raw)     # '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'  
  
struct.pack_into("iii", buf, 0, 1, 2, -1)  
print repr(buf.raw)     # '\x01\x00\x00\x00\x02\x00\x00\x00\xff\xff\xff\xff'  
  
print struct.unpack_from("iii", buf, 0)     # (1, 2, -1)  

具体内容请参考Python手册 struct 模块
Python手册 struct 模块:http://docs.python.org/library/struct.html#module-struct
struct 类型表

image.png

Notes:
The '?'conversion code corresponds to the _Booltype defined by C99. If this type is not available, it is simulated using a char. In standard mode, it is always represented by one byte.
New in version 2.6.The 'q' and 'Q' conversion codes are available in native mode only if the platform C compiler supports C long long, or, on Windows, __int64. They are always available in standard modes.
New in version 2.2.
When attempting to pack a non-integer using any of the integer conversion codes, if the non-integer has a [index()(http://blog.csdn.net/ithomer/article/details/reference/datamodel.html#object.index) method then that method is called to convert the argument to an integer before packing. If no index()
method exists, or the call to index()
raises TypeError
, then the int()
method is tried. However, the use of int()
is deprecated, and will raise DeprecationWarning
.
Changed in version 2.7: Use of the index()
method for non-integers is new in 2.7.
Changed in version 2.7: Prior to version 2.7, not all integer conversion codes would use the int()
method to convert, and DeprecationWarning
was raised only for float arguments.

For the 'f'and 'd'conversion codes, the packed representation uses the IEEE 754 binary32 (for 'f) or binary64 (for 'd') format, regardless of the floating-point format used by the platform.

The 'P' format character is only available for the native byte ordering (selected as the default or with the '@' byte order character). The byte order character '=' chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the 'P' format is not available.

A format character may be preceded by an integral repeat count. For example, the format string '4h'
means exactly the same as 'hhhh'
.
Whitespace characters between formats are ignored; a count and its format must not contain whitespace though.

For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting string always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).
The 'p' format character encodes a “Pascal string”, meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack()
is too long (longer than the count minus 1), only the leading count-1
bytes of the string are stored. If the string is shorter than count-1
, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack()
, the 'p'
format character consumes count bytes, but that the string returned can never contain more than 255 characters.
For the 'P'format character, the return value is a Python integer or long integer, depending on the size needed to hold a pointer when it has been cast to an integer type. A NULL pointer will always be returned as the Python integer 0. When packing pointer-sized values, Python integer or long integer objects may be used. For example, the Alpha and Merced processors use 64-bit pointer values, meaning a Python long integer will be used to hold the pointer; other platforms use 32-bit pointers and will use a Python integer.
For the '?' format character, the return value is either True or False. When packing, the truth value of the argument object is used. Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,287评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,346评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,277评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,132评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,147评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,106评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,019评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,862评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,301评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,521评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,682评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,405评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,996评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,651评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,803评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,674评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,563评论 2 352

推荐阅读更多精彩内容