Python: binascii模块

binascii模块提供了二进制到不同类型编码ASCII字符串之间的变换函数。包括16进制、base64、RLE等等。

其主要函数是一些列a2b_xxxb2a_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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值