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

前端 未结 5 1544
渐次进展
渐次进展 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:52

    def binary_converter(arr):
        total = 0
        for index, val in enumerate(reversed(arr)):
            total += (val * 2**index)
        print total
    
    
    In [14]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])
    In [15]: binary_converter(b)
    1285
    In [9]: b = np.array([0,0,0,0,0,1,0,1])
    In [10]: binary_converter(b)
    5
    

    or

    b = np.array([1,0,1,0,0,0,0,0,1,0,1])
    sum(val * 2**index for index, val in enumerate(reversed(b)))
    

提交回复
热议问题