In python, how would I convert a list of different length numbers to a list the same ascii characters?

Question:

I have a list of numbers:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]

I am trying to convert the list from integers to ascii characters of the same number before converting them to hex. I am running into trouble figuring out how to convert the entire list when there are some numbers with more than one digit.

I have tried:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
b = f'0x{ord(str(a)):x}'  
c = int(b, base=16)

which throws the error: ord() expected a character, but string of length 2 found.

A variation of it:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
separated_digits = [int(digit) for number in a for digit in str(number)]
ascii_chars_hexed = [f'0x{ord(str(digit)):x}' for digit in separated_digits]

works if I split the numbers in a into single digits, but I need the character output of the double digit numbers to be based upon the 2 digits rather than each individually.

I am expecting it to output:

[0x32, 0x32, 0x1e, 0x31, 0x1e, 0x36, 0x33, 0x1e, 0x30, 0x39, 0x34, 0x1e, 0x31, 0x1e, 0x31, 0x1d]`

Any thoughts?

Asked By: Sean Mckay

||

Answers:

To convert a list of integers to a list of ASCII characters in hexadecimal format, you can use a list comprehension like this:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
ascii_chars_hexed = [f'0x{ord(chr(num)):x}' for num in a]

This will convert each integer in the a list to the corresponding ASCII character using the chr function, and then convert the character to its hexadecimal representation using the ord function and the f’0x{:x}’ string format. The resulting list will be:

['0x32', '0x32', '0x1e', '0x31', '0x1e', '0x36', '0x33', '0x1e', '0x30', '0x39', '0x34', '0x1e', '0x31', '0x1e', '0x31', '0x1d']

Note that the double-digit numbers are being correctly converted to the ASCII characters based on their integer values, not their individual digits.

Answered By: Plam50

It’s an odd data format, but the following does what you want. Convert the single-digit numbers to a string and get their ASCII value. It would make more sense to store the ASCII value of the ‘2’ in the string as the integer 50 to begin with, for example.

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
print([f'{ord(str(n)) if n < 10 else n:#x}' for n in a])

Output:

['0x32', '0x32', '0x1e', '0x31', '0x1e', '0x36', '0x33', '0x1e', '0x30', '0x39', '0x34', '0x1e', '0x31', '0x1e', '0x31', '0x1d']
Answered By: Mark Tolonen
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.