Python struct模塊

有的時候須要用python處理二進制數據,好比,存取文件,socket操做時.這時候,能夠使用python的struct模塊來完成.能夠用 struct來處理c語言中的結構體.python

struct模塊中最重要的三個函數是pack(), unpack(), calcsize()c++

pack(fmt, v1, v2, ...)     按照給定的格式(fmt),把數據封裝成字符串(其實是相似於c結構體的字節流)socket

unpack(fmt, string)       按照給定的格式(fmt)解析字節流string,返回解析出來的tuple函數

calcsize(fmt)                 計算給定的格式(fmt)佔用多少字節的內存spa

 

struct中支持的格式以下表:指針

 

Format C Type Python 字節數
x pad byte no value 1
c char string of length 1 1
b signed char integer 1
B unsigned char integer 1
? _Bool bool 1
h short integer 2
H unsigned short integer 2
i int integer 4
I unsigned int integer or long 4
l long integer 4
L unsigned long long 4
q long long long 8
Q unsigned long long long 8
f float float 4
d double float 8
s char[] string 1
p char[] string 1
P void * long

注1.q和Q只在機器支持64位操做時有意思code

注2.每一個格式前能夠有一個數字,表示個數orm

注3.s格式表示必定長度的字符串,4s表示長度爲4的字符串,可是p表示的是pascal字符串blog

注4.P用來轉換一個指針,其長度和機器字長相關內存

注5.最後一個能夠用來表示指針類型的,佔4個字節爲了同c中的結構體交換數據,還要考慮有的c或c++編譯器使用了字節對齊,一般是以4個字節爲單位的32位系統,故而struct根據本地機器字節順序轉換.能夠用格式中的第一個字符來改變對齊方式.定義以下:

 

Character Byte order Size and alignment
@ native native            湊夠4個字節
= native standard        按原字節數
< little-endian standard        按原字節數
> big-endian standard       按原字節數
! network (= big-endian)

standard       按原字節數

 

 1     import struct  
 2       
 3     # 定義數據  
 4     a = "hello"  
 5     b = "world!"  
 6     c = 20  
 7     d = 42.56  
 8       
 9     # 打包  
10     binStr = struct.pack("5s6sif", a, b, c, d)  
11     print len(binStr)  
12     binStr2 = struct.pack("i", c)  
13       
14     # 解包  
15     e, f, g, h = struct.unpack("5s6sif", binStr)  
16     print e, f, g, h  
17       
18     # 注意unpack返回的是tuple,若是不按規定格式書寫,則返回值將改變類型  
19     i, = struct.unpack("i", c)  
20     print i  
21     i = struct.unpack("i", c)  
22     print i  
23       
24     # 計算轉換字節長度  
25     print struct.calcsize("5s6sif")  
相關文章
相關標籤/搜索