Search code examples
pythonhexascii

How to convert a hex list to a list of ASCII values?


Let's use as an example the hex string 0x790x760x7d0x7d0x80.

ct=input()
hex_list=ct.split('0x')
print(hex_list)
ascii_values=[]
for i in hex_list:
    if i!="" :
       (ascii_values).append(ascii(i))
print(ascii_values)

I'm getting this output:

['', '79', '76', '7d', '7d', '80']
["'79'", "'76'", "'7d'", "'7d'", "'80'"]

But the desired output would be the hex values converted into ASCII.


Solution

  • This will convert from to a list of bytes to ASCII, but 0x80 is invalid ASCII character code. See below:

    ct = '0x790x760x7d0x7d0x80'
    hex_list = ct.split('0x')
    ascii_values=[]
    for i in hex_list:
        print(i)
        if i != '':
            try:
                bytes_object = bytes.fromhex(i)
                ascii_string = bytes_object.decode("ASCII")
                ascii_values.append(ascii(ascii_string))
            except UnicodeDecodeError:
                print('Invalid ASCII... skipping...')
    print(ascii_values)
    

    See the answer here regarding 0x80.