Python提供了一个struct
模块来解决bytes
和其他二进制数据类型的转换。
struct
的pack
函数把任意数据类型变成bytes
:
>>> import struct
>>> struct.pack('>I', 10240099)
b'x00x9c@c'
pack
的第一个参数是处理指令,'>I'
的意思是:
>
表示字节顺序是big-endian,也就是网络序,I
表示4字节无符号整数。
后面的参数个数要和处理指令一致。
unpack
把bytes
变成相应的数据类型:
>>> struct.unpack('>IH', b'xf0xf0xf0xf0x80x80')
(4042322160, 32896)
根据>IH
的说明,后面的bytes
依次变为I
:4字节无符号整数和H
:2字节无符号整数。
所以,尽管Python不适合编写底层操作字节流的代码,但在对性能要求不高的地方,利用struct
就方便多了。
struct
模块定义的数据类型可以参考Python官方文档:
https://docs.python.org/3/library/struct.html#format-characters
Windows的位图文件(.bmp)是一种非常简单的文件格式,我们来用struct
分析一下。
首先找一个bmp文件,没有的话用“画图”画一个。
读入前30个字节来分析:
>>> s = b'x42x4dx38x8cx0ax00x00x00x00x00x36x00x00x00x28x00x00x00x80x02x00x00x68x01x00x00x01x00x18x00'
BMP格式采用小端方式存储数据,文件头的结构按顺序如下:
两个字节:'BM'表示Windows位图,'BA'表示OS/2位图;
一个4字节整数:表示位图大小;
一个4字节整数:保留位,始终为0;
一个4字节整数:实际图像的偏移量;
一个4字节整数:Header的字节数;
一个4字节整数:图像宽度;
一个4字节整数:图像高度;
一个2字节整数:始终为1;
一个2字节整数:颜色数。
所以,组合起来用unpack
读取:
>>> struct.unpack('<ccIIIIIIHH', s)
(b'B', b'M', 691256, 0, 54, 40, 640, 360, 1, 24)
结果显示,b'B'
、b'M'
说明是Windows位图,位图大小为640x360,颜色数为24。
请编写一个bmpinfo.py
,可以检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数。
# -*- coding: utf-8 -*-
#检查任意文件是否是位图文件,如果是,打印出图片大小和颜色数
import os, struct
def bmpinfo(thePath):
if os.path.isfile(thePath):
with open(thePath, 'rb') as f:
bThirty = f.read(30) # 读入前30个字节
if len(bThirty) < 30:
print('Not a bmp file!')
return
infos = struct.unpack('<ccIIIIIIHH', bThirty)
if infos[0] != b'B' or infos[1] != b'M':
print('Not a bmp file!')
return
print('The bmp file is %s * %s, and colors are %s.' % (infos[6], infos[7], infos[9]))
else:
print('File not exists!')
if __name__ == '__main__':
print("Please input a bmp file's full path:")
p = input()
bmpinfo(p)