1

I have a numpy array: ch=[1, 2, 3, 4, 20, 25]

How can i write it in: b'\x01\x02\x03\x04\x14\x19'

Note: i do not want to convert each integer to binary. Is there any function available to do it directly in one step?

2
  • ch is a numpy array Commented Aug 9, 2021 at 11:12
  • import numpy as geek ch=geek.array([1, 2, 3, 4, 20, 25]) x=bytes(ch) print(x) Commented Aug 9, 2021 at 11:12

2 Answers 2

2

You can use bytes bult-in and pass the sequence:

>>> ch=[1, 2, 3, 4, 20, 25]
>>> bytes(ch)
b'\x01\x02\x03\x04\x14\x19'

On a side note, what you are showing is a python list, not a numpy array.

But, if you want to operate on numpy array, you can first convert it to a python list:

>>> bytes(np.array(ch).tolist())
b'\x01\x02\x03\x04\x14\x19'

When you directly try to_bytes() on the numpy array for above data:

>>> np.array(ch).tobytes()
b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x14\x00\x00\x00\x19\x00\x00\x00'

The above output is also right, the only difference is due to the data type, if you print it, you'll know that it's numpy.int32, which is 32 bit means 32/8=4 bytes i.e. the number of bytes required to represent each of the values.

>>> np.array(ch).dtype
dtype('int32')

If, you convert it to 8-bit i.e. 1 byte number, the output will be same, as using bytes bultin over a list:

>>> np.array(ch).astype(np.int8).tobytes()
b'\x01\x02\x03\x04\x14\x19'
Sign up to request clarification or add additional context in comments.

6 Comments

This doesn't work for me. I get b'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x14\x00\x00\x00\x19\x00\x00\x00'
Working fine on Python 3.7.5 win10
You're operating on a list. OP specifically indicated a NumPy array.
@MattDMo, but the input presented is not a numpy array.
How can we chage little or big endian?
|
0

The following will work:

b"".join([int(item).to_bytes(1, "big") for item in ch])

First you iterate over the NumPy array, convert each np.int32 object to int, call int.to_bytes() on it, returning 1 byte in big-endian order (you could also use "little" here), then joining them all together.

Alternatively, you could call list() on the array, then pass it to the built-in bytes() constructor:

bytes(list(ch))

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.