在 Python 中将十六进制转换为 ASCII

在 Python 中使用 decode() 方法将十六进制转换为 ASCII

Python 2 中的 string.decode(encoding, error) 方法将已编码的字符串作为输入,并使用 encoding 参数中指定的编码方案对其进行解码。error 参数指定在发生错误时可以使用的错误处理方案,可以是 strictignore 和 replace

因此,要将十六进制字符串转换为 ASCII 字符串,我们需要将 string.decode() 方法的 encoding 参数设置为 hex。下面的示例代码演示了如何使用 string.decode() 方法在 Python 2 中将十六进制转换为 ASCII。

string = "68656c6c6f"
string.decode("hex")

输出:

hello

在 Python 3 中,bytearray.decode(encoding, error) 方法将字节数组作为输入,并使用 encoding 参数中指定的编码方案对其进行解码。

要在 Python 3 中解码字符串,我们首先需要将字符串转换为字节数组,然后使用 bytearray.decode() 方法对其进行解码。bytearray.fromhex(string) 方法可用于首先将字符串转换为字节数组。

下面的示例代码演示了如何使用 bytearray.decode() 和 bytearray.fromhex(string) 方法在 Python 3 中将十六进制字符串转换为 ASCII 字符串:

string = "68656c6c6f"
byte_array = bytearray.fromhex(string)
byte_array.decode()

输出:

hello

在 Python 中使用 codecs.decode() 方法将十六进制转换为 ASCII

codecs.decode(obj, encoding, error) 方法类似于 decode() 方法。它接受一个对象作为输入,并使用 encoding 参数中指定的编码方案对其进行解码。error 参数指定发生错误时要使用的错误处理方案。

在 Python 2 中,codecs.decode() 返回一个字符串作为输出,而在 Python 3 中,它返回一个字节数组。下面的示例代码演示了如何使用 codecs.decode() 方法将十六进制字符串转换为 ASCII 以及如何使用 str() 方法将返回的字节数组转换为字符串。

import codecs

string = "68656c6c6f"
binary_str = codecs.decode(string, "hex")
print(str(binary_str,'utf-8'))

输出:

hello