python如何封装数据

python如何封装数据

我把python用在通信领域,需要按位封装和操作数据,比如

struct Table{
BYTE id;
int reserved1:1;  //必须为1
int reserved2:1;        //必须为0
int reserved3:2;
int length:20;
int counter:8;
int crc_32;
}

这样的一个结构如何用python方便的表述和通过通过网络传输呢
看一看struct模块。
Format  C Type  Python  Notes  
x pad byte no value   
c char string of length 1   
b signed char integer   
B unsigned char integer   
h short integer   
H unsigned short integer   
i int integer   
I unsigned int long   
l long integer   
L unsigned long long   
q long long long (1)
Q unsigned long long long (1)
f float float   
d double float   
s char[] string   
p char[] string   
P void * integer
import struct

calcsize(...)
    calcsize(fmt) -> int
    Return size of C struct described by format string fmt.
    See struct.__doc__ for more on format strings.

pack(...)
    pack(fmt, v1, v2, ...) -> string
    Return string containing values v1, v2, ... packed according to fmt.
    See struct.__doc__ for more on format strings.

unpack(...)
    unpack(fmt, string) -> (v1, v2, ...)
    Unpack the string, containing packed C structure data, according
    to fmt.  Requires len(string)==calcsize(fmt).
    See struct.__doc__ for more on format strings.