3

Hello there, hope you are all doing well.

I am working on a little assignment right now. I have a string of a binary number, which I need to convert to decimal. I converted the string to a numpy array and then tried what I saw on this link's answer:

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

However, since my array has a size of 54, the solution is not working correctly, I am getting negative results whereas the correct value is a very large positive number.

 # data_binary = [0 1 1 1 0 1 1 1 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 1 1 0 1 0 0 1 1 0 1 0 1 1 1 0 0 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1]
data_decimal = data_binary.dot(1 << np.arange(data_binary.size)[::-1])

For example, the decimal equivalent of the data_binary in this instance is "8395915512384511", however my script calculates it as "1773014015".

Is there any method which you can suggest me to use to achieve my goal? Thank you so much in advance!

asked Feb 13, 2021 at 20:54

2 Answers 2

2

I am confused, you are saying "decimal" but I think you mean integer and not a float. In any case, python natively supports numbers written in binary:

x = 0b011101110101000000101001101001101011100000101111111111
print(x)

The "0b" tells python that the following integer is being displayed in binary. If your binary number is a string, then you need to use the int() function designed to convert from a string to an int:

x = int('011101110101000000101001101001101011100000101111111111',2)
print(x)

You are getting 1773014015 becuase you are using "int32", hence manual arithmetic on the entries will cause a cycle. If you use "int64" you get the correct answer.

import numpy as np
x = np.array([0,1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,0,1,0,1,1,1,0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1])
y = (x*2**np.arange(53,-1,-1,dtype='int64')).sum()
print(y)
y = x.dot(1 << np.arange(x.size,dtype='int64')[::-1])
print(y)
answered Feb 13, 2021 at 21:04
Sign up to request clarification or add additional context in comments.

1 Comment

For what it's worth, I believe the @kucar meant "decimal" as in "base 10".
1

Since already a numpy solution is given. Here is a pythonic way to do.

sum([j*(2**i) for i,j in list(enumerate(reversed(c)))])
8395915512384511

c is where your list of binary numbers are.

answered Feb 13, 2021 at 21:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.