user7148991
user7148991

Reputation:

Convert hex Ascii representation in a bytes object to Ascii string using Python3

I want to convert a variable containing a bytes object of Ascii data to a string.
Ex:

a=bytearray(b'31303031') 

I want to convert it to:

'1001'

How to do this in Python3?

Upvotes: 0

Views: 133

Answers (1)

kabanus
kabanus

Reputation: 26005

Convert each pair to integer from base 16, get the appropriate character, and concatenate:

''.join(chr(int(a[i:i+2], 16)) for i in range(0,len(a),2))

Of course, you do not really have a bytes object of hexadecimals, but a string. So, get back the string, make a real hexadecimal bytes object, and decode that is another option:

bytes.fromhex(a.decode('ascii')).decode('ascii')

Upvotes: 1

Related Questions