如何使用 Python 将 .txt 文件中的整数解码为 ascii?

问题描述

我仍然是学习 Python 3 的初学者。 我尝试读取包含一行数字的“New_Memtrace.txt”文件,如下所示: 0000000000000000FFDF102F0000000000000000FFFFFFFF0000000000000000137F05000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000012CCF3F00000000000000004000014000000000000000001F0000000000000000000000000000000000000000000000

请注意,该文件中没有任何空格或换行符(纯数字行)。 我想将数字的每 2 位数字的数据解码为 ASCII 字符作为十六进制(例如:00 作为 NUL,1F 作为美国在 ascii 表上)

然后,我尝试编写此代码,但运行时出现一些错误

in_file = open ("New_Memtrace.txt",'r')
in_byte_string = in_file.read()
bytes_object = bytes.fromhex(in_byte_string) #converts to bytes object
print(bytes_object)
ascii_string = bytes_object.decode("ASCII")  #convert to ASCII representation
print(ascii_string)

转换为字节对象成功完成,输出

b'\x00\x00\x00\x00\x00\x00\x00\x00\xff\xdf\x10/\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x13\x7f\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01,\xcf?\x00\x00\x00\x00\x00\x00\x00\x00@\x00\x01@\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

但是,输出下面出现了一个错误

Traceback (most recent call last):
...
ascii_string = bytes_object.decode("ASCII")         #convert to ASCII representation
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 8: ordinal not in
range(128)

我该怎么办?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)