Convert binary (0|1) numpy to integer or binary-string?

前端 未结 5 1289
渐次进展
渐次进展 2021-02-19 20:29

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)
         


        
5条回答
  •  太阳男子
    2021-02-19 20:58

    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:

    import numpy as np
    def bin2int(bits):
        return np.right_shift(np.packbits(bits, -1), bits.size).squeeze()
    

    Since normally if you are using numpy you care about speed then the fastest implementation for > 64-bit results is:

    import gmpy2
    def bin2int(bits):
        return gmpy2.pack(list(bits[::-1]), 1)
    

    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:

    def bin2int(bits):
        total = 0
        for shift, j in enumerate(bits[::-1]):
            if j:
                total += 1 << shift
        return total
    

    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.

提交回复
热议问题