python处理二进制数据
2016-09-06 18:50
435 查看
struct
处理二进制数据离不开python的struct模块,struct理解上你可以把它理解为c语言的结构体,使用该模块的pack和unpack方法,可以很容易的把二进制数据转换为常用的类型数据,如整型、字符型等结构体如下:
struct Header { unsigned short id; char[4] tag; unsigned int version; unsigned int count; }
unpack
将二进制数据流解析为常用的数据类型,例如:python arsc_file = open(file, "rb") #二进制读取文件 data = arsc_file.read(12) #读取12字节 table_type_2,head2,file4,package4 = struct.unpack("2H2I", data) #将这12个字节分拆为2个unsigned short(H)和2个unsigned int(I)类型数据
pack
把常用的数据类型打包成二进制数据,例如:new_head2 = 2 head2 = 1 file4 = 8 new_data = struct.pack("2H2I4H", table_type_2, new_head2, file4, package4,head2,head2,head2,head2) #把常用的类型数据转换二进制流,参数一是二进制流格式组成
struct里面规定的数据类型表
Format | C Type | Python | 字节数 |
---|---|---|---|
x | pad byte | no value | 1 |
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 or long | 4 |
l | long | integer | 4 |
L | unsigned long | long | 4 |
q | long long | long | 8 |
Q | unsigned long | long long | 8 |
f | float | float | 4 |
d | double | float | 8 |
s | char[] | string | 1 |
p | char[] | string | 1 |
P | void * | long |
相关文章推荐
- python处理二进制数据
- python处理二进制数据的方法
- python中使用struct模块处理二进制数据
- python处理二进制数据
- python处理二进制数据
- python2.7和python3.4网络编程处理二进制数据区别
- python的struct处理二进制数据,主机字节序和网络字节序
- python中用struct模块处理二进制数据(转)
- python处理二进制数据的方法
- 利用Python对二进制数据进行按位处理
- python处理二进制数据
- 【转】python中用struct模块处理二进制数据
- Python使用struct处理二进制 解析二进制数据 解析socket数据
- python 中关于struct处理二进制数据
- python处理二进制数据
- python中用struct模块处理二进制数据(转)
- python处理二进制数据
- 用struct模块处理二进制数据
- mscomm控件接收二进制数据后的处理
- python 处理csv数据