将numpy数组转换为十六进制字节数组 [英] Convert numpy array to hex bytearray

查看:3454
本文介绍了将numpy数组转换为十六进制字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python 2.7中将一个numpy数组转换为一个字节串。假设我的numpy数组 a 是一个简单的 2x2 数组,看起来像这样:

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

我的问题是,如何将这个数组转换为一串字节或bytearray,输出如下所示:

  \x01\x0A\x10\xff 

或同样好:

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


解决方案

np.int8 类型,您可以使用 tobytes() 来获得您指定的输出:

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

请注意,我的终端打印 \x0A 作为换行符 \\\

$在数组 a 中调用内建函数 bytes 中的Python也是如此尽管 tobytes()允许您指定内存布局(按照文档)。



如果 a 有一个类型,它为每个数字使用更多的字节,你的字节字符串可能会填充很多不需要的空字节。您可以投射到较小的类型,也可以使用切片(或类似)。例如,如果 a 类型为 int64

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

作为一个观点,您还可以使用 view 将NumPy数组的底层内存解释为字节。例如,如果 a 仍然是 int64 键入:

 >>> a.view('S8')
数组([[b'\x01',b'\\\
'],
[b'\x10',b'\xff'] ],dtype ='| S8')


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

解决方案

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

这篇关于将numpy数组转换为十六进制字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆