python struct中pack和unpack

struct.pack() and struct.unpack()

用于C语言数据与Python数据类型间转换。

 

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)

 

 

>>> from struct import *
>>> pack('hhl', 1, 2, 3)    #本例是大尾字节序
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')    #参数必须是类型fmt
8
>>> pack('ci', '*', 0x12131415)   # 存数时自动对齐字节,传说中的字节对齐,如果加上等号则进行优化,也就是说不填充字节
'*\x00\x00\x00\x12\x13\x14\x15'
>>> pack('ic', 0x12131415, '*')
'\x12\x13\x14\x15*'
>>> calcsize('ci')   如calcsize('=ci')  结果是:5
8
>>> calcsize('ic') 
5
>>>pack('llh0l', 1, 2, 3)        #加0在后面填充两个字节的0,不是很清楚,留待以后操作验明。
'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'
#抄袭一把,(:
 
 
   
   
   
   
  1. # 取前5个字符,跳过4个字符华,再取3个字符   
  2. format = '5s 4x 3s'  
  3. 2. 使用struck.unpack获取子字符串   
  4. import struct   
  5. print struct.unpack(format, 'Test astring')   
  6. #('Test', 'ing')   
  7. 来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。   
  8. import struct   
  9. theString = 'He is not very happy'   
  10. format = '2s 1x 2s 5x 4s 1x 5s'   
  11. print ' '.join(struct.unpack(format, theString))   
  12. 输出结果:   
  13. He is very happy  

 

你可能感兴趣的:(python,linux,python,c语言,网络)