TransWikia.com

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

Stack Overflow Asked by Ger Cas on December 20, 2021

I have an hexadecimal string like this:

s = 'x83 x01x86x01ptx89oA'

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

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

One Answer

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

In [25]: data = b'x83 x01x86x01ptx89oA'

In [26]: data.hex()
Out[26]: '83200186017009896f41'

Answered by bigbounty on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP