title: Convert decimal range to Numpy array, with each bit being an array element
body: <p>I have created a small function that takes as input an integer, <code>length</code>, and returns a <code>numpy</code> <code>array</code> of the binary representation of all <code>2**length</code> integer numbers in the range <code>[0:2**length-1]</code>.</p>
  
  <pre><code>import numpy as np
  
  def get_bitstrings(length):
    # We need to binary-fy 2^length numbers.
    iterations = 2**length
    # Pre-allocate memory.
    the_array = np.zeros((iterations, length))
    # Go through all decimals in the range [0:iterations-1]
    for num in range(iterations):
      # Get binary representation in string format with 'length' zeroes padded
      t_string = '{f_num:0{f_width}b}'.format(f_num=num, f_width=length)
      # Convert to a Python list
      t_list   = list(t_string)
      # Convert to Numpy array and store.
      the_array[num,:] = np.array(t_list)
  
    return the_array
  
  if __name__ == '__main__':
    var1 = get_bitstrings(2)
    var2 = get_bitstrings(3)
    print('var1:\n{}\n'.format(var1))
    print('var2:\n{}\n'.format(var2))
  </code></pre>
  
  <p>which yields:</p>
  
  <pre><code>var1:
  [[ 0.  0.]
   [ 0.  1.]
   [ 1.  0.]
   [ 1.  1.]]
  
  var2:
  [[ 0.  0.  0.]
   [ 0.  0.  1.]
   [ 0.  1.  0.]
   [ 0.  1.  1.]
   [ 1.  0.  0.]
   [ 1.  0.  1.]
   [ 1.  1.  0.]
   [ 1.  1.  1.]]
  </code></pre>
  
  <p>The process includes getting a binary representation of each integer number as a string (with 0s padded before it such that the length is constant at <code>length</code>), converting the string into a Python list, and then converting the list into a <code>numpy</code> <code>array</code>.</p>
  
  <p>I found that to be the only way to satisfy the requirement that each bit is an entry in the array – i.e., bitstring <code>1010</code> is a <code>1x4</code> <code>numpy</code> <code>array</code> and not simply an integer in a <code>1x1</code> array. But I am sure there are better alternatives, hence the question.</p>
  
  <p>The problem, as you can imagine, is that this is inefficient. I was wondering whether I can improve this by using Python/Numpy trickery.</p>
  
  <p><em>Edit</em>:
  I used to do this in MATLAB with this snippet:</p>
  
  <blockquote>
    <p>t_length = 5;
    dc = [0:2^t_length-1]';
    bc = rem(floor(dc*pow2(-(t_length-1):0)),2);</p>
  </blockquote>
  
  <p>But I am a complete noob when it comes to Python/Numpy! Maybe it'll inspire someone. <code>:-)</code></p>