额。。。。最近被python的数据类型折腾得有点够呛了。。。struct的pack和unpack可以解决很多和C兼容的数据类型问题,但是有很多trick...
pack可以把一个C语言类似struct的结构转换成一个python的string数据结构,有了str结构,就可以进行write操作什么的了。
from python help
The optional first format char indicates byte order, size and alignment:
@: native order, size & alignment (default)
=: native order, std. size & alignment
<: little-endian, std. size & alignment
>: big-endian, std. size & alignment
!: same as >
The remaining chars indicate types of args and must match exactly;
these can be preceded by a decimal repeat count:
x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;
h:short; H:unsigned short; i:int; I:unsigned int;
l:long; L:unsigned long; f:float; d:double.
Special cases (preceding decimal count indicates length):
s:string (array of char); p: pascal string (with count byte).
Special case (only available in native format):
P:an integer type that is wide enough to hold a pointer.
Special case (not in native mode unless 'long long' in platform C):
q:long long; Q:unsigned long long
Whitespace between formats is ignored.
用法就是 string = struct.pack(format, data) ,format就是上面的usage
例:
struct.pack('<I', 0x12345678),会将0x12345678转换成一个小端的 unsigned int并保存成str。
>>> struct.pack('<I', 0x12345678)
'xV4\x12
>>> struct.pack('<Ic', 0x12345678, 'k')
'xV4\x12k'
struct
{
unsigned int a,
char b
};
>>> struct.pack('<Ic2B', 0x12345678, 'k', 1, 0)
'xV4\x12k\x01\x00'
2B代表说是2个字节,2代表连续2个B。
>>> struct.pack('<Ic2B', 0x12345678, 'k', 1, 266)
__main__:1: DeprecationWarning: 'B' format requires 0 <= number <= 255
'xV4\x12k\x01\n'
>>> struct.calcsize('cBi')
8
>>> struct.calcsize('i')
4
>>> struct.calcsize('c')
1
>>> struct.calcsize('B')
1
>>> struct.calcsize('cBi')
8
>>> struct.calcsize('=cBi')
6
不带=号,会进行对齐操作,加等号则优化。
>>> struct.pack('<Ic2BH', 0x12345678, 'k', 1, 233, 0x1234)
'xV4\x12k\x01\xe94\x12'
>>> struct.unpack('<Ic2BH','xV4\x12k\x01\xe94\x12')
(305419896, 'k', 1, 233, 4660)
unpack注意!这里返回的是一个tuple!
转载自:http://blog.chinaunix.net/space.php?uid=9185047&do=blog&id=445020