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!

1
  • Try koo.dot(1 << np.arange(koo.size)[::-1]) Commented Apr 26, 2021 at 16:47

3 Answers 3

1
>>> 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
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need .tolist(). str.join() will happily use any iterable, which a numpy array is one.
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

Comments

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])])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.