Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2927650
  • 博文数量: 401
  • 博客积分: 12926
  • 博客等级: 上将
  • 技术积分: 4588
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-22 14:51
文章分类

全部博文(401)

文章存档

2015年(16)

2014年(4)

2013年(12)

2012年(82)

2011年(98)

2010年(112)

2009年(77)

分类: Python/Ruby

2009-06-04 14:57:20

额。。。。最近被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('
>>> struct.pack(''xV4\x12

>>> struct.pack(''xV4\x12k'
struct
{
  unsigned int a,
  char         b
};

>>> struct.pack(''xV4\x12k\x01\x00'
2B代表说是2个字节,2代表连续2个B。

>>> struct.pack('__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(''xV4\x12k\x01\xe94\x12'
>>> struct.unpack('(305419896, 'k', 1, 233, 4660)
unpack注意!这里返回的是一个tuple!
阅读(12121) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~