2

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?

2 Answers 2

3
'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')
Sign up to request clarification or add additional context in comments.

1 Comment

not for python 3
1

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.