1

I have a string like this:

string = "b'\\xf4\\xf0\\xf2\\xef\\xf8\\xf2\\xee'"

So far I have come up with this:

arr = np.array([int(s_num, 16) for s_num in re.findall(r'x([a-f0-9]{2})', string)], dtype=np.uint8)

For large strings this gets really slow. What is the best way to convert the string to a numpy array (of data type np.uint8)? Thanks.

1
  • 1
    You really shouldn't have that string to begin with, but rather b'\\xf4\\xf0\\xf2\\xef\\xf8\\xf2\\xee'. How did you get that? Commented Mar 1, 2022 at 14:55

1 Answer 1

2

What about:

from ast import literal_eval

np.frombuffer(literal_eval(string), dtype=np.uint8)

output: array([244, 240, 242, 239, 248, 242, 238], dtype=uint8)

Sign up to request clarification or add additional context in comments.

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.