0

I want to create random integers and convert them in binary format via NumPy matrix. I wrote the following code:

def toBinary(C):
    l = []
    for x in C:
        b = [int(i) for i in bin(x)[2:]]
        l = np.vstack((l, np.array(b)))
    return l

list_vectors = [random.randint(0, 2 ** 64) for _ in range(2)]
print(toBinary(list_vectors))

But I still don't know how to solve this error:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(toBinary(list_vectors))
  File "test.py", line 27, in toBinary
    l = np.vstack((l, np.array(b)))
  File "/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py", line 234, in vstack
    return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly

Any suggestion is highly appreciated.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Ethan C.
  • 239
  • 4
  • 13

2 Answers2

2

The issue here is that the conversion to binary does not always return a binary number of same length. If the first integer in C is, let's say 3, it'll give '0b11'. Stack this in the array, then try to convert 17. Oops, you're trying to concatenate '11' and '1001' together, it won't work.

What I did here then, is forcing the converted binary number length to 10 using the format() function (Convert to binary and keep leading zeros in Python).

import numpy as np
import numpy.random as random

def toBinary(C):
    binaries_length = 10
    bin_format = f'#0{binaries_length+2}b'
    array_rows = len(C)
    l = np.empty((array_rows, binaries_length))
    for i, x in enumerate(C):
        l[i,:] = np.array([int(i) for i in format(x, bin_format)[2:]])
    return l

list_vectors = [random.randint(0, 2 * 64) for _ in range(10)]

print(toBinary(list_vectors))

Also, the returned array is pre-allocated, since you now perfectly know what size it will be :

binaries_length = 10
bin_format = f'#0{10+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))

By the way, the call random.randint(0, 2 ** 64) also triggers an exception because 2 ** 64 is insanely too high so I changed it to 2*64 here.

To go further, you can find the optimal binary length by finding the maximum of C.

MaximGi
  • 543
  • 3
  • 12
0

Try this, it will return a list instead of array, so make the necessary adjustments if you like:

def toBinary(C):
    l = []
    for x in C:
        b = [i for i in bin(x)[2:]]
        a="".join(b)
        a=int(a)
        l.append(a)
return l
NatanMish
  • 11
  • 4