Python struct pack/unpack

1. struct.pack用于将Python的值根据格式符,转换为字符串, 代码“pack.py”如下,

#!/usr/bin/env python  
import sys  
import struct  

# initialization  
a = 20  
b = 400   

# pack
str = struct.pack("ii", a, b)  
print 'length: ', len(str)      # length:  8  
print repr(str)                 # Little endian: '\x14\x00\x00\x00\x90\x01\x00\x00'(本地字符流通常采用小端编码,即低位字节放前面;网络字节流通常采用大端编码,即高位字节放前面)

2. struct.unpack做的工作刚好与struct.pack相反,用于将字节流转换成python数据类型,代码“unpack.py”如下,

#!/usr/bin/env python  
import sys  
import struct  

# initialization  
a = 20  
b = 400   

# pack
str1 = struct.pack("ii", a, b)  
print 'length: ', len(str1)      # length:  8  
print repr(str1)                 # Little endian: '\x14\x00\x00\x00\x90\x01\x00\x00' (本地字符流通常采用小端编码,即低位字节放前面;网络字节流通常采用大端编码,即高位字节放前面)


# unpack  
str2 = struct.unpack("ii", str1)  
print 'length: ', len(str2)          # length:  2  
print str2                           # (20, 400)  
print repr(str2)                     # (20, 400)  

3. python网络字节流混合编解码示例

import struct

a = 1
b = 2
c = 3
d = 4

str1 = struct.pack("ii", a, b)
str2 = struct.pack("ii", c, d)
str3 = struct.pack(", a, b) + struct.pack(">ii", c, d) # combine big endian and little endian encodings

print repr(str1)
print repr(str2)
print repr(str3)

str3_head = str3[:8]
str3_tail = str3[8:]

print struct.unpack(", str3_head)
print struct.unpack(">ii", str3_tail)

参考
1. http://blog.csdn.net/linuxheik/article/details/51882958

你可能感兴趣的:(计算机网络)