在python中明智地将二进制值追加到列

时间:2018-10-23 06:24:29

标签: python-3.x numpy multidimensional-array character-encoding

我希望将字符串的二进制值明智地存储在数组列中。

st = "hello world"
st = st.encode('utf-8')
# binary value for letter 'h'
bin(st[0]) -> '0b1101000'
# binary value for letter 'e'
bin(st[1]) -> '0b1100101'

以此类推...

我想将这些二进制字符串存储在数组中,如下所示:

0  1  
0  0
0  1
1  0
0  0
1  1
1  1
b  b
0  0

谢谢, Neeraj

2 个答案:

答案 0 :(得分:0)

将字符串转换为二进制的更Python方式是:

st = "hello world"
m = map(bin,bytearray(st))

这将创建一个列表m,如下所示:

print(m)
['0b1101000',
 '0b1100101',
 '0b1101100',
 '0b1101100',
 '0b1101111',
 '0b100000',
 '0b1110111',
 '0b1101111',
 '0b1110010',
 '0b1101100',
 '0b1100100']

然后您可以简单地将其转置并使用逗号加入。

m_transpose = [ [j] for j in [ ','.join(i[::-1]) for i in m ]]

    In [1038]: m_transpose
    Out[1038]: 
 [['0,0,0,1,0,1,1,b,0'],
 ['1,0,1,0,0,1,1,b,0'],
 ['0,0,1,1,0,1,1,b,0'],
 ['0,0,1,1,0,1,1,b,0'],
 ['1,1,1,1,0,1,1,b,0'],
 ['0,0,0,0,0,1,b,0'],
 ['1,1,1,0,1,1,1,b,0'],
 ['1,1,1,1,0,1,1,b,0'],
 ['0,1,0,0,1,1,1,b,0'],
 ['0,0,1,1,0,1,1,b,0'],
 ['0,0,1,0,0,1,1,b,0']]

让我知道这是否是您想要的。

答案 1 :(得分:0)

您可以使用np.fromstringnp.unpackbits

>>> a = np.unpackbits(np.fromstring(st, np.uint8)).reshape((8, -1), order='F')[::-1]
>>> a
array([[0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1],
       [1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0],
       [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)

此字符不包含b字符。如果您必须具备以下条件:

>>> np.r_['0,2,1', a.astype('U1')[:7], np.full(a.shape[1], 'b'), np.full(a.shape[1], '0')]
array([['0', '1', '0', '0', '1', '0', '1', '1', '0', '0', '0'],
       ['0', '0', '0', '0', '1', '0', '1', '1', '1', '0', '0'],
       ['0', '1', '1', '1', '1', '0', '1', '1', '0', '1', '1'],
       ['1', '0', '1', '1', '1', '0', '0', '1', '0', '1', '0'],
       ['0', '0', '0', '0', '0', '0', '1', '0', '1', '0', '0'],
       ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
       ['1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1'],
       ['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'],
       ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']],
      dtype='<U1')