I have strings of hex, for exemple '01ff6fee32785e366f710df10cc542B4' and I am trying to convert them (efficiently) into an int array 2 characters by 2 characters like [1,255,...].
I tried
c = '8db6796fee32785e366f710df10cc542B4'
c2=[int(x,16) for x in c]
but it only takes the characters one by one. Can i do it without using a for loop (I might be wrong but if think it would be slower) ?
You could range(..) over substrings of length 2:
c = '8db6796fee32785e366f710df10cc'
c2=[int(c[i:i+2],16) for i in range(0,len(c),2)]
So i iterates of the string with steps of 2 and you take a substring of length 2 from i to i+2 (exclusive) with c[i:i+2]. These you convert by taking int(..,16).
For your sample input it generates:
>>> c='8db6796fee32785e366f710df10cc'
>>> [int(c[i:i+2],16) for i in range(0,len(c),2)]
[141, 182, 121, 111, 238, 50, 120, 94, 54, 111, 113, 13, 241, 12, 12]
The last element is 12 because the length of your string is odd, so it takes c as the last element to parse.
For an alternate approach
hex_string = '8db6796fee32785e366f710df10cc542B4'
a = bytearray.fromhex(hex_string)
b = list(a)
print(b)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With