准确地讲,Python没有专门处理字节的数据类型。但由于
在Python中,比方说要把一个32位无符号整数变成字节,也就是4个长度的str,你得配合位运算符这么写: >>> n = 10240099 >>> b1 = chr((n & 0xff000000) >> 24) >>> b2 = chr((n & 0xff0000) >> 16) >>> b3 = chr((n & 0xff00) >> 8) >>> b4 = chr(n & 0xff) >>> s = b1 + b2 + b3 + b4 >>> s '\x00\x9c@c' 非常麻烦。如果换成浮点数就无能为力了。
好在Python提供了一个
>>> import struct >>> struct.pack('>I', 10240099) '\x00\x9c@c'
后面的参数个数要和处理指令一致。
>>> struct.unpack('>IH', '\xf0\xf0\xf0\xf0\x80\x80') (4042322160, 32896)
根据
所以,尽管Python不适合编写底层操作字节流的代码,但在对性能要求不高的地方,利用
https://docs.python.org/2/library/struct.html#format-characters
Windows的位图文件(.bmp)是一种非常简单的文件格式,我们来用 首先找一个bmp文件,没有的话用“画图”画一个。 读入前30个字节来分析: >>> s = '\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00' BMP格式采用小端方式存储数据,文件头的结构按顺序如下:
两个字节:
所以,组合起来用 >>> struct.unpack('<ccIIIIIIHH', s) ('B', 'M', 691256, 0, 54, 40, 640, 360, 1, 24)
结果显示,
请编写一个 转载请保留固定链接: https://linuxeye.com/program/2471.html |