`

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

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics