Is there a shortcut to Convert binary (0|1) numpy array to integer or binary-string ? F.e.
b = np.array([0,0,0,0,0,1,0,1])
=> b is 5
np.packbits(b)
My timeit results:
b.dot(2**np.arange(b.size)[::-1])
100000 loops, best of 3: 2.48 usec per loop
b.dot(1 << np.arange(b.size)[::-1])
100000 loops, best of 3: 2.24 usec per loop
# Precompute powers-of-2 array with a = 1 << np.arange(b.size)[::-1]
b.dot(a)
100000 loops, best of 3: 0.553 usec per loop
# using gmpy2 is slower
gmpy2.pack(list(map(int,b[::-1])), 1)
100000 loops, best of 3: 10.6 usec per loop
So if you know the size ahead of time, it's significantly faster to precompute the powers-of-2 array. But if possible, you should do all computations simultaneously using matrix multiplication like in Geoffrey Anderson's answer.