Convert a byte array to single bits in a array [Python 3.5]
<p>I am looking for a operation witch converts my byte array:</p>

<pre><code>mem = b'\x01\x02\xff'
</code></pre>

<p>in something like this:</p>

<pre><code>[ [0 0 0 0 0 0 0 1]
  [0 0 0 0 0 0 1 0]
  [1 1 1 1 1 1 1 1] ]
</code></pre>

<p>These are operations that I tried:</p>

<pre><code>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)
</code></pre>

<p>This code will crash at line 4.. <code>IndexError: index 255 is out of bounds for axis 0 with size 9</code>
Otherwise, it crash at line 5.. <code>IndexError: too many indices for array</code></p>

<p><strong>These are my Questions:</strong></p>

<p>Why are the number of spaces different after the conversion from hex to int?</p>

<p>Is that the reason that my next conversion from int to bin failed?</p>

<p>Finally, what is wrong with my <code>list</code> operation?</p>

<p>Thank you for your help! :)</p>

<p>To solve IndexError you can use  <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html#numpy.ndindex" rel="nofollow"><code>numpy.ndindex</code></a>:</p>

<pre><code>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:07b}'.format(mem[b]) for b in np.ndindex(mem.shape)])

data= np.array([list(mem[b]) for b in np.ndindex(mem.shape)]) #finally convert to single bits

print(data)
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>[['0', '0', '0', '0', '0', '0', '1'] ['0', '0', '0', '0', '0', '1', '0']
 ['1', '1', '1', '1', '1', '1', '1', '1']]
</code></pre>

python arrays hex bit