Viacheslav Viacheslav - 5 days ago 5
Python Question

hex2chars & chars2hex functions

I have a function hex2chars:

def hex2chars(data):
result = ''.join(chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2))
return result

data = '9ede820b31ae92d83be578a7ab8ce906c4ead38943ee73a36e058fac33a0a85861ec46f9cf1ec3d11c0ec8b14aea470c37c1eb87375aca94d9b214e90a0b73f8214d929675768c3d88c95b5618438685ec99cf50ccd846902be6104335482c1ae0136f2dfcfd97e072c38c8d142c9f92f25f3b911bac5beaa51184eb1e6c3169b3b58ec8e094b988648136f6b4bde59def0bce7f03e0cf321f95d067e3319f31dd099513c0d7'


How I can create a chars2hex function?

Answer

The reverse conversion is easy. You just need to use ord, the inverse function of chr, and format the result to 2 digit hexadecimal:

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

def chars2hex(data):
    return ''.join(['%02x' % ord(c) for c in data])

data = '9ede820b31ae92d83be578a7ab8ce906c4ead38943ee73a36e058fac33a0a85861ec46f9cf1ec3d11c0ec8b14aea470c37c1eb87375aca94d9b214e90a0b73f8214d929675768c3d88c95b5618438685ec99cf50ccd846902be6104335482c1ae0136f2dfcfd97e072c38c8d142c9f92f25f3b911bac5beaa51184eb1e6c3169b3b58ec8e094b988648136f6b4bde59def0bce7f03e0cf321f95d067e3319f31dd099513c0d7'

s = hex2chars(data)
new_data = chars2hex(s)
print data == new_data

output

True

Note that you need to use a different approach in Python 3.

However, there's no need to code these functions yourself: you can use the functions in the standard binascii module to write code that will work correctly on Python 2 or Python 3.

Comments