Search code examples
pythonpython-3.xdecodebinaryfiles

How to decode hexadecimal string with "b" at the beggining?


I have an hexadecimal string like this:

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

I decoded to hex values like this, getting the following output.

>>> ' '.join('{:02x}'.format(ord(ch)) for ch in s)
'83 20 01 86 01 70 09 89 6f 41'

But now I have issues to decode a hex string that is exactly as the previous one, but this comes from a binary file. and has a b at the begining. The error below:

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

How would be the way to fix this? Thanks


Solution

  • Use .hex() method on the byte string instead.

    In [25]: data = b'\x83 \x01\x86\x01p\t\x89oA'
    
    In [26]: data.hex()
    Out[26]: '83200186017009896f41'