python struct (对python obj进行编码解码)

参考文档:

http://docs.python.org/2/library/struct.html
http://blog.163.com/ws__fyy/blog/static/12243381720123181013666/
http://blog.163.com/kongdelu2009@yeah/blog/static/1119952072009102562126194/

 

# -*- coding: utf-8 -*-
import struct
import sys
import os

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

1). byte order: Native byte order is big-endian or little-endian, depending on the host system.
    ①Intel X86 / AMD64(x86-64) ==> little-endian
    ②Motorola 68000 / PowerPC G5 ==> big-endian
    ③ARM / Intel Itanium feature switchable endianness (bi-endian)
2). size:
    ①Native size are determined using the C compiler's sizeof expression.
    ②Standard size depends only on the 'format character'
3). alignment:

2. format character
Format 	C Type 	            Python type 	    Standard size
x 	pad byte 	    no value 	  	 
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 	            4 
l 	long 	            integer 	            4
L 	unsigned long 	    integer 	            4 
q 	long long 	    integer 	            8 
Q 	unsigned long long  integer 	            8 
f 	float 	            float 	            4 
d 	double 	            float 	            8 
s 	char[] 	            string 	  	 
p 	char[] 	            string 	  	 
P 	void * 	            integer 	  
'''

#检查大端小端
print sys.byteorder

s='abcde'
a=20
b=400

'''
3. python obj-->pack-->str
'''
packed_str = struct.pack('< 5s2i',s,a,b)
#<      : little endian, standard side, none alignment
# whitespaces are ignored.
#5s     : 5 is the "size" of the string
#2i     : 2 is the "repeat count"
#print len(s)
print struct.calcsize('< 5s2i')
print repr(s)
print type(s)

'''
4. str-->pack-->python obj
'''
(s, a, b) = struct.unpack('<5s2i', packed_str)
print s
print a
print b

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值