Python:struct模組的pack、unpack

來源:互聯網
上載者:User

標籤:padding   python   alc   title   app   sdn   har   理解   一個   

mport struct

pack、unpack、pack_into、unpack_from

 1 # ref: http://blog.csdn<a href="http://lib.csdn.net/base/dotnet" class=‘replace_word‘ title=".NET知識庫" target=‘_blank‘ style=‘color:#df3434; font-weight:bold;‘>.NET</a>/JGood/archive/2009/06/22/4290158.aspx   2    3 import struct   4    5 #pack - unpack   6 print   7 print ‘===== pack - unpack =====‘   8    9 str = struct.pack("ii", 20, 400)  10 print ‘str:‘, str  11 print ‘len(str):‘, len(str) # len(str): 8   12   13 a1, a2 = struct.unpack("ii", str)  14 print "a1:", a1  # a1: 20  15 print "a2:", a2  # a2: 400  16   17 print ‘struct.calcsize:‘, struct.calcsize("ii") # struct.calcsize: 8  18   19   20 #unpack  21 print  22 print ‘===== unpack =====‘  23   24 string = ‘test astring‘  25 format = ‘5s 4x 3s‘  26 print struct.unpack(format, string) # (‘test ‘, ‘ing‘)  27   28 string = ‘he is not very happy‘  29 format = ‘2s 1x 2s 5x 4s 1x 5s‘  30 print struct.unpack(format, string) # (‘he‘, ‘is‘, ‘very‘, ‘happy‘)  31   32   33 #pack  34 print  35 print ‘===== pack =====‘  36   37 a = 20  38 b = 400  39   40 str = struct.pack("ii", a, b)  41 print ‘length:‘, len(str) #length: 8  42 print str  43 print repr(str) # ‘/x14/x00/x00/x00/x90/x01/x00/x00‘  44   45   46 #pack_into - unpack_from  47 print  48 print ‘===== pack_into - unpack_from =====‘  49 from ctypes import create_string_buffer  50   51 buf = create_string_buffer(12)  52 print repr(buf.raw)  53   54 struct.pack_into("iii", buf, 0, 1, 2, -1)  55 print repr(buf.raw)  56   57 print struct.unpack_from("iii", buf, 0)  

 

運行結果:

[[email protected] Python]$ python struct_pack.py

===== pack - unpack =====
str: ?
len(str): 8
a1: 20
a2: 400
struct.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)

 

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值。下面的例子將兩個整數轉換為字串(位元組流):

 1 #!/usr/bin/env python   2 #encoding: utf8   3    4 import sys   5 reload(sys)   6 sys.setdefaultencoding("utf-8")   7    8 import struct   9   10 a = 20  11 b = 400   12 str = struct.pack("ii", a, b)  13 print ‘length: ‘, len(str)          # length:  8  14 print str                           # 亂碼:   15 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),該函數返回一個元組。 

下面是一個簡單的例子:

 1 #!/usr/bin/env python   2 #encoding: utf8   3    4 import sys   5 reload(sys)   6 sys.setdefaultencoding("utf-8")   7    8 import struct   9   10 a = 20  11 b = 400   12   13 # pack  14 str = struct.pack("ii", a, b)  15 print ‘length: ‘, len(str)          # length:  8  16 print str                           # 亂碼:   17 print repr(str)                     # ‘\x14\x00\x00\x00\x90\x01\x00\x00‘  18   19 # unpack  20 str2 = struct.unpack("ii", str)  21 print ‘length: ‘, len(str2)          # length:  2  22 print str2                           # (20, 400)  23 print repr(str2)                     # (20, 400)  

3、 struct.calcsize
struct.calcsize用於計算格式字串所對應的結果的長度,如:struct.calcsize(‘ii‘),返回8。因為兩個int類型所佔用的長度是8個位元組。

1 import struct  2 print "len: ", struct.calcsize(‘i‘)       # len:  4  3 print "len: ", struct.calcsize(‘ii‘)      # len:  8  4 print "len: ", struct.calcsize(‘f‘)       # len:  4  5 print "len: ", struct.calcsize(‘ff‘)      # len:  8  6 print "len: ", struct.calcsize(‘s‘)       # len:  1  7 print "len: ", struct.calcsize(‘ss‘)      # len:  2  8 print "len: ", struct.calcsize(‘d‘)       # len:  8  9 print "len: ", struct.calcsize(‘dd‘)      # len:  16 

4、 struct.pack_into、 struct.unpack_from
這兩個函數在Python手冊中有所介紹,但沒有給出如何使用的例子。其實它們在實際應用中用的並不多。Google了很久,才找到一個例子,貼出來共用一下:

 1 #!/usr/bin/env python   2 #encoding: utf8   3    4 import sys   5 reload(sys)   6 sys.setdefaultencoding("utf-8")   7    8 import struct   9 from ctypes import create_string_buffer  10   11 buf = create_string_buffer(12)  12 print repr(buf.raw)     # ‘\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00‘  13   14 struct.pack_into("iii", buf, 0, 1, 2, -1)  15 print repr(buf.raw)     # ‘\x01\x00\x00\x00\x02\x00\x00\x00\xff\xff\xff\xff‘  16   17 print struct.unpack_from("iii", buf, 0)     # (1, 2, -1) 

struct 類型表

 

Format C Type Python type Standard size Notes
x pad byte no value    
c char string of length 1 1  
b signed char integer 1 (3)
B unsigned char integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsigned short integer 2 (3)
i int integer 4 (3)
I unsigned int integer 4 (3)
l long integer 4 (3)
L unsigned long integer 4 (3)
q long long integer 8 (2), (3)
Q unsigned long long integer 8 (2), (3)
f float float 4 (4)
d double float 8 (4)
s char[] string 1  
p char[] string    
P void * integer   (5), (3)

Python:struct模組的pack、unpack

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.