struct

作者 新城 日期 2017-09-01
struct

struct

在Python中,比方说要把一个32位无符号整数变成字节,也就是4个长度的bytes,你得配合位运算符这么写:

1
2
3
4
5
6
7
n = 10240099
b1 = (n & 0xff000000) >> 24
b2 = (n & 0xff0000) >> 16
b3 = (n & 0xff00) >> 8
b4 = n & 0xff
bs = bytes([b1, b2, b3, b4])
print(bs) #输出b'\x00\x9c@c

Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换。

struct的pack函数把任意数据类型变成bytes:

1
2
import struct
struct.pack('>I', 10240099) #输出 b'\x00\x9c@c'

pack的第一个参数是处理指令,’>I’的意思是:

表示字节顺序是big-endian,也就是网络序,I表示4字节无符号整数。
后面的参数个数要和处理指令一致。

unpack把bytes变成相应的数据类型

1
struct.unpack('>IH', b'\xf0\xf0\xf0\xf0\x80\x80')  #转换成相应的数据类型(4042322160, 32896)
1
2
3
4
5
import hashlib

md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
print(md5.hexdigest())

####