首页 > 解决方案 > UnicodeDecodeError:“utf-8”编解码器无法解码位置 2 中的字节 0xf3:无效的继续字节

问题描述

我想将十六进制字符串转换为 ASCII,我尝试了多种方法来转换它,但每次都会抛出相同的错误。

编码:

hexFile = open('message', 'rb')
fileData = hexFile.read()
dataString = str(fileData, 'UTF-8')
bytes_object = bytes.fromhex(dataString)
ascii_string = bytes_object.decode("ASCII")
print(ascii_string)

错误:

第 130 行,在 dataString = str(fileData, 'UTF-8')

UnicodeDecodeError:“utf-8”编解码器无法解码位置 2 中的字节 0xf3:无效的继续字节

标签: pythonhexascii

解决方案


你可以binascii为此使用模块

import binascii
with open('message','rb') as f:
    print(binascii.b2a_uu(f.read()).decode()) #decode will return string from bytes

但请记住,它最多只能做 45 个数据长度。更多你可以使用binascii.b2a_base64. 见文档


推荐阅读