如何解码以"b"开头的十六进制字符串?
How to decode hexadecimal string with "b" at the beggining?
我有一个这样的十六进制字符串:
s = '\x83 \x01\x86\x01p\t\x89oA'
我像这样解码为十六进制值,得到以下输出。
>>> ' '.join('{:02x}'.format(ord(ch)) for ch in s)
'83 20 01 86 01 70 09 89 6f 41'
但现在我在解码与前一个完全相同的十六进制字符串时遇到问题,但它来自二进制文件。并且开头有一个 b
。错误如下:
with open('file.dat', 'rb') as infile:
data = infile.read()
>>> data
b'\x83 \x01\x86\x01p\t\x89oA'
>>> ' '.join('{:02x}'.format(ord(ch)) for ch in data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
TypeError: ord() expected string of length 1, but int found
如何解决这个问题?谢谢
改为对字节字符串使用 .hex()
方法。
In [25]: data = b'\x83 \x01\x86\x01p\t\x89oA'
In [26]: data.hex()
Out[26]: '83200186017009896f41'
我有一个这样的十六进制字符串:
s = '\x83 \x01\x86\x01p\t\x89oA'
我像这样解码为十六进制值,得到以下输出。
>>> ' '.join('{:02x}'.format(ord(ch)) for ch in s)
'83 20 01 86 01 70 09 89 6f 41'
但现在我在解码与前一个完全相同的十六进制字符串时遇到问题,但它来自二进制文件。并且开头有一个 b
。错误如下:
with open('file.dat', 'rb') as infile:
data = infile.read()
>>> data
b'\x83 \x01\x86\x01p\t\x89oA'
>>> ' '.join('{:02x}'.format(ord(ch)) for ch in data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
TypeError: ord() expected string of length 1, but int found
如何解决这个问题?谢谢
改为对字节字符串使用 .hex()
方法。
In [25]: data = b'\x83 \x01\x86\x01p\t\x89oA'
In [26]: data.hex()
Out[26]: '83200186017009896f41'