binascii模块提供了二进制到不同类型编码ASCII字符串之间的变换函数。包括16进制、base64、RLE等等。
其主要函数是一些列a2b_xxx和b2a_xxx函数。
其中:
- a2b代表ascii to binary;
- b2a代表binary to ascii;其中,b2a_hex可用hexlify函数替代
- xxx表示编码类型,如hex、base64、rle等。
此外,配合struct模块,可以将各种数据类型,变换为字符串,再与二进制字符串进行变换。
例子如下:
import binascii
import struct
txt1 = 'hello the world'
data1 = binascii.b2a_hex(txt1)
print(repr(data1))
# '68656c6c6f2074686520776f726c64'
txt1b = binascii.a2b_hex(data1)
print(repr(txt1b))
# 'hello the world'
txtd = [1, 2, 3, 4, 5]
txt2 = struct.pack('5B', * txtd)
data2 = binascii.b2a_hex(txt2)
print(repr(data2))
# '0102030405'
txt2b = binascii.a2b_hex(data2)
print(repr(txt2b))
# '\x01\x02\x03\x04\x05'