Files
Python_CookBook_repo/6.数据编码与处理/9.编码和解码十六进制数字.py
2025-09-10 16:12:45 +08:00

22 lines
557 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import base64, binascii
if __name__ == '__main__':
s = b'Hello World!'
# 将字节串以十六进制编码
h = binascii.b2a_hex(s)
print(h)
# 将数据从十六进制解码成字节串
b = binascii.a2b_hex(h)
print(b)
# 同理在熟悉的base64模块我们也能实现同样的功能
h = base64.b16encode(s)
print(h)
b = base64.b16decode(h)
print(b)
# 个人感觉base64的API更加干净
# 对了如果想要将数据以unicode输出可以使用一次decode
print(h.decode('ascii'))