Reputation: 35408
I have the following string:
"0c a8 f0 d6 02 00 00 00 00 d0 1c d1 10 d2 00 d3 00 d7 01 d4 78 20 ff"
As you can see, it contains hex values and I want to transform it into an array of bytes, using Python 2.4.4 (NOT 3.x, so I don't have the useful bytearray
). The only way to achieve it as per my knowledge is something like:
i = []
i.append(0x0c)
i.append(0xa8)
i.append(0xf0) # ... and so on
.....
z = ''.join(chr(c) for c in i)
But this is horrible. Any good hint how to solve this efficiently?
Upvotes: 2
Views: 5490
Reputation: 4182
You can decode string replacing all whitespaces
s = "0c a8 f0 d6 02 00 00 00 00 d0 1c d1 10 d2 00 d3 00 d7 01 d4 78 20 ff"
x = s.replace(" ", "").decode('hex')
or You can use generator statement for example
x = ''.join(chr(int(i, 16)) for i in s.split())
Upvotes: 1
Reputation: 10450
'0c a8 f0 d6 02 00 00 00 00 d0 1c d1 10 d2 00 d3 00 d7 01 d4 78 20 ff'.replace(' ', '').decode('hex')
Upvotes: 3