2

I want to convert a numpy array to a bytestring in python 2.7. Lets say my numpy array a is a simple 2x2 array, looking like this:

[[1,10],
 [16,255]]

My question is, how to convert this array to a string of bytes or bytearray with the output looking like:

\x01\x0A\x10\xff

or equally well:

bytearray(b'\x01\x0A\x10\xff')

1 Answer 1

4

Assuming a is an array of np.int8 type, you can use tobytes() to get the output you specify:

>>> a.tobytes()
b'\x01\n\x10\xff'

Note that my terminal prints \x0A as the newline character \n.

Calling the Python built in function bytes on the array a does the same thing, although tobytes() allows you to specify the memory layout (as per the documentation).

If a has a type which uses more bytes for each number, your byte string might be padded with a lot of unwanted null bytes. You can either cast to the smaller type, or use slicing (or similar). For example if a is of type int64:

>>> a.tobytes()[::8]
b'\x01\n\x10\xff

As a side point, you can also interpret the underlying memory of the NumPy array as bytes using view. For instance, if a is still of int64 type:

>>> a.view('S8')
array([[b'\x01', b'\n'],
       [b'\x10', b'\xff']], dtype='|S8')
Sign up to request clarification or add additional context in comments.

1 Comment

Just for someone seeing that in the future: 'tobyte()' could also be 'tostring()' in some numpy releases, moreover 'bytes(a)' doesn't work for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.