繁体   English   中英

如何在开头用“b”解码十六进制字符串?

[英]How to decode hexadecimal string with “b” at the beggining?

我有一个像这样的十六进制字符串:

s = '\x83 \x01\x86\x01p\t\x89oA'

我像这样解码为十六进制值,得到以下 output。

>>> ' '.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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM