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)
works but only for 8 bit values ..if the numpy is 9 or more elements it generates 2 or more 8bit values. Another option would be to return a string of 0|1 ...
What I currently do is :
ba = bitarray()
ba.pack(b.astype(np.bool).tostring())
#convert from bitarray 0|1 to integer
result = int( ba.to01(), 2 )
which is ugly !!!
One way would be using
dot-product
with2-powered
range array -Sample run -
Alternatively, we could use bitwise left-shift operator to create the range array and thus get the desired output, like so -
If timings are of interest -
Reverse process
To retrieve back the binary array, use
np.binary_repr
alongwithnp.fromstring
-or
Using numpy for conversion limits you to 64-bit signed binary results. If you really want to use numpy and the 64-bit limit works for you a faster implementation using numpy is:
Since normally if you are using numpy you care about speed then the fastest implementation for > 64-bit results is:
If you don't want to grab a dependency on gmpy2 this is a little slower but has no dependencies and supports > 64-bit results:
The observant will note some similarities in the last version to other Answers to this question with the main difference being the use of the << operator instead of **, in my testing this led to a significant improvement in speed.