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

Viewed 64

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.

2 Answers

You can treat the strings as a series of groups of four characters. From each group, drop the 0x prefix using string slicing and zip(), and then you can use map() to turn the tuples from zip() into strings representing the desired hex values.

From there, you can turn these strings into the desired characters using int() to get the integer value that the string represents, and chr() to get the corresponding ASCII character.

data = "0x790x760x7d0x7d0x80"
ascii_values = list(map(''.join, zip(data[2::4], data[3::4])))
result = [chr(int(val, 16)) for val in ascii_values]

print(result)

This outputs:

['y', 'v', '}', '}', '\x80']

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.

Related