Skip to main content
 首页 » 编程设计

python之将字节数组转换为数组中的单个位 [Python 3.5]

2024年10月17日6artech

我正在寻找一个转换字节数组的操作:

mem = b'\x01\x02\xff' 

像这样:

[ [0 0 0 0 0 0 0 1] 
  [0 0 0 0 0 0 1 0] 
  [1 1 1 1 1 1 1 1] ] 

这些是我尝试过的操作:

import numpy as np 
 
mem = b'\x01\x02\xff' #define my input 
mem = np.fromstring(mem, dtype=np.uint8) #first convert to int 
 
#print(mem) give me "[  1   2 255]" at this piont 
 
mem = np.array(['{0:08b}'.format(mem[b]) for b in mem]) #now convert to bin 
data= np.array([list(mem[b]) for b in mem]) #finally convert to single bits 
 
print(data) 

此代码将在第 4 行崩溃。IndexError:索引 255 超出尺寸为 9 的轴 0 的范围 否则,它会在第 5 行崩溃。IndexError: too many indices for array

这些是我的问题:

为什么hex转int后空格个数不一样?

这就是我下一次从 int 到 bin 的转换失败的原因吗?

最后,我的list操作有什么问题?

感谢您的帮助! :)

请您参考如下方法:

使用解包位:

>>> import numpy as np 
>>> mem = b'\x01\x02\xff' 
>>> x = np.fromstring(mem, dtype=np.uint8) 
>>> np.unpackbits(x).reshape(3,8) 
array([[0, 0, 0, 0, 0, 0, 0, 1], 
       [0, 0, 0, 0, 0, 0, 1, 0], 
       [1, 1, 1, 1, 1, 1, 1, 1]], dtype=uint8) 

文档

来自帮助(np.unpackbits):

unpackbits(...)
unpackbits(myarray, axis=None)

Unpacks elements of a uint8 array into a binary-valued output array.

Each element of myarray represents a bit-field that should be unpacked into a binary-valued output array. The shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done along the axis specified.