微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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 举报,一经查实,本站将立刻删除。