现在的位置: 首页 > 综合 > 正文

python struct模块

2018年08月16日 ⁄ 综合 ⁄ 共 1427字 ⁄ 字号 评论关闭

最近看一点python的代码,发现struct这个包在处理网络编程上非常强大,pack和unpack函数能很轻松地将数据组包拆包,如下所示:

  1. #! /usr/bin/env python  
  2.   
  3. import socket, struct, time, re  
  4.   
  5. if __name__ == '__main__':  
  6.     num1 = 5  
  7.     num2 = 10  
  8.     str1 = 0x00001000  
  9.     str2 = 0x00002000  
  10.     cha1 = 3  
  11.     cha2 = 65  
  12.     pack_res = struct.pack('!HHIIBB', num1, num2, str1, str2, cha1, cha2)  
  13.     print "after pack "  
  14.     print "pack_res", pack_res  
  15.   
  16.     n1,n2,s1,s2,c1,c2 = struct.unpack("!HHIIBB", pack_res)  
  17.     print "after unpack"  
  18.     print "n1 = ", n1  
  19.     print "n2 = ", n2  
  20.     print "s1 = ", s1  
  21.     print "s2 = ", s2  
  22.     print "c1 = ", c1  
  23.     print "c2 = ", c2  
  24.       
  25.     ''''' 
  26.     after pack  
  27.     pack_res  
  28.     ??????????... 
  29.     after unpack 
  30.     n1 =  5 
  31.     n2 =  10 
  32.     s1 =  4096 
  33.     s2 =  8192 
  34.     c1 =  3 
  35.     c2 =  65 
  36.     '''  

官方手册有格式参数的说明,摘录如下,其中感叹号表示网络序字节流,H代表无符号短整型,B代表无符号字符,I代表无符号整形。

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

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    
p char[] string    
P void * integer   (5), (3)

抱歉!评论已关闭.