Aswin G Aswin G - 6 months ago 26
Python Question

Convert hex-encoded string to decimal array in python

For example, I want

68656c6c6f
, the hex encoding of the word 'hello', to be converted into
[104, 101, 108, 108, 111]
. I need it as a list, not as a continuous integer.

x=int("68656c6c6f",16)
is apparently not what I'm looking for because it gives me
448378203247
instead, which makes sense. But it's not my solution.

Answer

Try this,

s = "68656c6c6f"
x = [int(s[i:i+2], 16) for i in range(0, len(s), 2)]

print(x)
# Output
[104, 101, 108, 108, 111]

Or use ord as mentioned by @Liam

s = "68656c6c6f"
x = [ord(c) for c in s.decode('hex')]

print(x)
# Output
[104, 101, 108, 108, 111]