0

I have task of converting an array with binary numbers into a decimal number. My array code looks like this:

koo = np.random.randint(2, size=10)
print(koo)

Example of the output is:

[1 0 1 0 0 0 0 0 1 0]

And what I'm supposed to do is to turn it into a string (1010000010), in order to then turn it into a decimal number (642). What could be a way to do this?

For this task I have to create it with the array, I cannot use np.binary_repr()

I have tried solving it with the solution offered here, but when working on it the numbers would be wildly different from what's true (i.e.: 1011111010 was 381 according to the program, while in reality it's 762)

Anybody knows how to solve this problem? Thank you in advance!

Zuza
  • 3
  • 2

3 Answers3

0

you can use a list comprehension to enumerate the digits from end to beginning and then calculate the numbers in base ten, then sum. for example:

np.sum([digit * 2 ** i for i, digit in enumerate(koo[::-1])])

0
>>> koo = np.random.randint(2, size=10)
>>> koo
array([1, 1, 0, 0, 0, 0, 1, 1, 1, 1])

>>> binary_string =  ''.join(koo.astype('str').tolist())
>>> binary_string
'1100001111'

>>> binary_val = int('1100001111', 2)
>>> binary_val
783
imdevskp
  • 2,103
  • 2
  • 9
  • 23
  • You don't need `.tolist()`. `str.join()` will happily use any iterable, which a numpy array is one. – Reti43 Apr 26 '21 at 16:29
0

At first, convert Numpy array to string by simply appending elements. Then, using int(), recast the string using base of 2.

koo = np.random.randint(2, size=10)
print(koo)
binaryString = ""
for digit in koo:
    binaryString += str(digit)
print(binaryString)
decimalString = int(binaryString, base=2)
print(decimalString)

An example run:

[0 0 1 0 1 0 0 0 0 0]
0010100000
160