Convert numpy array to hex bytearray

僤鯓⒐⒋嵵緔 提交于 2019-12-19 11:43:08

问题


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:


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


来源:https://stackoverflow.com/questions/33136281/convert-numpy-array-to-hex-bytearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!