1

I am using python-3.x, and I am trying to convert a list of a numpy array "Binary's" to decimal numbers, as I know I need to convert these Binary's first to Strings then I can convert them to Decimal ex:

1.Binary = 101011111 >>> 2.String= '101011111' >>>>> 3.decimal= 351

binary= '101011111'
binary = int(binary, 2)
print (binary)

But is there any way to convert a list of Binary's straightaway to decimal I don't want to convert them to Strings?

1.Binary = 101011111 >>> 2.decimal= 351

My input is:
Type: int64
Size:(3, 8)
Value: array:([[1,0,0,1,1,0,0,0],
               [1,1,1,1,1,0,0,0],
               [1,0,0,1,1,1,0,1]])

the output:  ([[152],
               [248],
               [157]])

 

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
azeez
  • 469
  • 3
  • 6
  • 17

1 Answers1

1

Since your binary numbers are built from arrays, each array position represents a certain base value (2**n) or a left shift (<< n). This, together with the broadcasting of numpy, allows a solution like:

binary = np.array([[1, 0, 0, 1, 1, 0, 0, 0],
                   [1, 1, 1, 1, 1, 0, 0, 0],
                   [1, 0, 0, 1, 1, 1, 0, 1]])

wordlength = binary.shape[1]
shift = np.arange(wordlength-1, -1, -1)

decimal = np.sum(binary << shift, 1)

Thus, I generate a simple range from n-1 down to 0 which I then broadcast and use to shift each binary digit to get its value. Then I just sum up the values along the dimension of each binary number.

JohanL
  • 6,671
  • 1
  • 12
  • 26