Bootstrap

PYTHON简单的16进制转字符串

PYTHON 以字符串形式存在的16进制数,转为该16进制对应的ascii字符串比较麻烦。

如:

hex_str = ‘7468616e6b20796f752076657279206d75636821’ # thank you very much!

首先要将其转为16进制数
hex = hex_str.encode(‘utf-8’)

然后再转为字符串
str_bin = binascii.unhexlify(hex)
str = str_bin.decode(‘utf-8’)

函数:

import binascii

def hexStr_to_str(hex_str):
    hex = hex_str.encode('utf-8')
    str_bin = binascii.unhexlify(hex)
    return str_bin.decode('utf-8')

if __name__ == "__main__":
	hex_str = '7468616e6b20796f752076657279206d75636821' 
	print(hexStr_to_str(hex_str))

简单方法来了

我们知道,base16编码就是将字符用16进制表示

’a’ =base16=> b’61’

那么简单对16进制字符串进行base16解码即可

import base64

hex_str = '7468616e6b20796f752076657279206d75636821' 
print(base64.b16decode(hex_str.upper()))
;