1

I'm really new in python. I have a numpy array of str that I woud like to convert, as it is, to a bytes string.

v = np.array([['2B', '0E', '00', '00', '00', '00', '00', '00']])

Result should be:

b'\x2b\x0e\x00\x00\x00\x00\x00\x00'

I tried bytes, encode, and many other exotic solutions but without success. Could anyone help me with that, please ?

2
  • 1
    Did you try tobytes? Commented Jun 10, 2020 at 19:53
  • Running [v = np.array([['2B', '0E', '00', '00', '00', '00', '00', '00']]) v.tobytes()] returns [b'2\x00\x00\x00B\x00\x00\x000\x00\x00\x00E\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x000\x00\x00\x00'] Commented Jun 11, 2020 at 4:47

2 Answers 2

1

You can use bytes

bytes([int(x, 16) for x in v[0]])

Output

b'+\x0e\x00\x00\x00\x00\x00\x00'
Sign up to request clarification or add additional context in comments.

Comments

0

Me looking at your array and the desired result suggests

that the result simply added a \x to and lower-cased each string.

Like so:

import numpy as np
v = np.array([['2B', '0E', '00', '00', '00', '00', '00', '00']])
v = '\\'+'\\x'.join([b.lower() for i in v for b in i])
print(v.encode('utf8'))

Output:

b'\\2b\\x0e\\x00\\x00\\x00\\x00\\x00\\x00'

3 Comments

Wenn I run your code, it returns [b'\\2b\\x0e\\x00\\x00\\x00\\x00\\x00\\x00'] ?
The extra backslashes are only there to escape backslashes. It is actually still equivalent to it without extra backslashes. Just try print(v.encode('utf8').decode('asciil')).
But wenn I run [v = np.array([['2B', '0E', '00', '00', '00', '00', '00', '00']]) v = '\\'+'\\x'.join([b.lower() for i in v for b in i]) vb=v.encode('utf8') vb==b'\x2b\x0e\x00\x00\x00\x00\x00\x00'] it returns [false] ?

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.