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!

kucar
  • 245
  • 3
  • 13

2 Answers2

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)
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15
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.

Ajay
  • 5,267
  • 2
  • 23
  • 30