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("<ii", 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("<ii", str3_head)
print struct.unpack(">ii", str3_tail)

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值