convert hex encoded string to ASCII - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: convert hex encoded string to ASCII (/thread-194.html) |
convert hex encoded string to ASCII - Skaperen - Sep-29-2016 given a string of hexadecimal characters that represent ASCII characters, i want to convert it to those ASCII characters. for example: '707974686f6e2d666f72756d2e696f' -> 'python-forum.io' in python 2 i can do .decode('hex') but this is gone in python3. so, i found this: codecs.decode(codecs.decode('707974686f6e2d666f72756d2e696f','hex'),'ascii')anything simpler that works in either python 2 or python 3 ? RE: convert hex encoded string to ASCII - j.crater - Sep-29-2016 How about codecs.decode("707974686f6e2d666f72756d2e696f", "hex")Does it give the result you want? RE: convert hex encoded string to ASCII - Vexis - Oct-02-2016 Personally, I've found the fromhex method of bytes to be useful. print(bytes.fromhex('7370616d')) # b'spam' RE: convert hex encoded string to ASCII - Skaperen - Oct-02-2016 (Sep-29-2016, 07:45 AM)j.crater Wrote: How about not in py 3. i want an ASCII or UTF-8 string, not an array of bytes. this why i added the 2nd call to codecs.decode(,"ascii"). RE: convert hex encoded string to ASCII - snippsat - Oct-02-2016 Quote:this why i added the 2nd call to codecs.decode(,"ascii")You don't need a second call,just add .decode('utf-8'). >>> codecs.decode("707974686f6e2d666f72756d2e696f", "hex").decode('utf-8') 'python-forum.io'It will work the same in Python 2.x >>> codecs.decode("707974686f6e2d666f72756d2e696f", "hex").decode('utf-8') u'python-forum.io'Strings are Unicode by default in Python 3.x. >>> u'python-forum.io' == 'python-forum.io' True |