Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a numpy Array of 1's and 0's to Decimal (Python)

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!

like image 610
kucar Avatar asked Jun 30 '26 07:06

kucar


1 Answers

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)
like image 115
Bobby Ocean Avatar answered Jul 01 '26 22:07

Bobby Ocean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!