Saturday, 20 November 2021

Python convert hex to ascii

I've been having trouble with this simple task of converting a string of hexadecimal digits to text. My research and testing were insufficient. While the characters are not from extended ascii table, this is a easy task. But my strings can and will include letters like "áðéíóþæ". The sting comes from snmp and in this example I will be using the word "Ísland" for this demo hex "cd 73 6c 61 6e 64" Here is one of the most promising code snipped

 
import binascii

def hex_to_ascii(hex_str):
    hex_str = hex_str.replace(' ', '').replace('0x', '').replace('\t', '').replace('\n', '')
    ascii_str = binascii.unhexlify(hex_str)
    return ascii_str
 
hex_input = 'cd 73 6c 61 6e 64'
ascii_output = hex_to_ascii(hex_input)

print(format(ascii_output))

The output was b'\xcdsland' so it does not encode the first letter like all me previous tempts. Finally I found this snipped:
 
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'

Next step was to fit join(chr) in my snipped like so..
   
import binascii

def hex_to_ascii(hex_str):
    hex_str = hex_str.replace(' ', '').replace('0x', '').replace('\t', '').replace('\n', '')
    ascii_str = binascii.unhexlify(hex_str)
    return ascii_str
 
hex_input = 'cd 73 6c 61 6e 64'
ascii_output = hex_to_ascii(hex_input)
ascii_output = ''.join(chr(i) for i in ascii_output)

print(format(ascii_output))

--cheers