[英]UnicodeDecodeError: 'ascii' codec can't decode byte 0xa7 in position 0: not in ordinal range (128)
I have a hex string represented as a list of single characters that contains some text.我有一个十六进制字符串,表示为包含一些文本的单个字符列表。 When I try to decode the hex with:当我尝试使用以下命令解码十六进制时:
for counter, i in enumerate(hexadecimal):
if counter % 2 == 0:
pass
else:
temp_list = hexadecimal[counter:counter + 2]
hex_string = ''.join(str(x) for x in temp_list)
bytes_string = bytes.fromhex(hex_string)
ascii_text += bytes_string.decode('ascii')
It works fine but when it encounters the number ['A', 7] it gives me this error.它工作正常,但是当它遇到数字 ['A', 7] 时,它给了我这个错误。 I assume it's because the character doesn't exist in ASCII, how do I make a readable character from that?我认为这是因为该字符在 ASCII 中不存在,我如何从中制作一个可读的字符?
EDIT:编辑:
An example input would be [6, 1, 6, 2, 6, 3]
which yields abc
as output.一个示例输入是[6, 1, 6, 2, 6, 3]
,它产生abc
为 output。
A program input is [0, 'F', 3, 4, 3, 0, 2, 'E', 3, 0, 3, 1, 5, 6, 2, 0, 3, 4, 3, 7, 3, 2, 3, 3, 4, 1, 4, 1, 3, 3, 5, 1]
which yields 40.01V 4723AA3Q
程序输入为[0, 'F', 3, 4, 3, 0, 2, 'E', 3, 0, 3, 1, 5, 6, 2, 0, 3, 4, 3, 7, 3, 2, 3, 3, 4, 1, 4, 1, 3, 3, 5, 1]
产生40.01V 4723AA3Q
If you want to be able to represent any byte as an acceptable character, you should use the Latin-1 or ISO-8859-1 encoding (2 names but same charset).如果您希望能够将任何字节表示为可接受的字符,则应使用 Latin-1 或 ISO-8859-1 编码(2 个名称但相同的字符集)。 Any byte is accepted, even if some are not printable characters.任何字节都被接受,即使有些不是可打印的字符。 The representation is the unicode character of same value (up to 255 of course) if it exists.如果存在,表示是相同值(当然最多 255)的 unicode 字符。
For you question, '\xa7'
will be the unicode character U+00A7 SECTION SIGN §
.对于您的问题, '\xa7'
将是 unicode 字符 U+00A7 SECTION SIGN §
。
So you just have to change your last line with:所以你只需要改变你的最后一行:
ascii_text += bytes_string.decode('Latin1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.