Converting binary to decimal integer output
Solution 1
Binary to Decimal
int(binaryString, 2)
Decimal to Binary
format(decimal ,"b")
Solution 2
There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:
- Train an AI algorithm to convert 32-binary number to decimal based.
- Predict a decimal representation from 32-binary.
See example and time comparison below:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
y = np.random.randint(0, 2**32, size=10_000)
def gen_x(y):
_x = bin(y)[2:]
n = 32 - len(_x)
return [int(sym) for sym in '0'*n + _x]
X = np.array([gen_x(x) for x in y])
model = LinearRegression()
model.fit(X, y)
def convert_bin_to_dec_ai(array):
return model.predict(array)
y_pred = convert_bin_to_dec_ai(X)
Time comparison:
This AI solution converts numbers almost x10 times faster than conventional way!
Solution 3
If you want/need to do it without int
:
sum(int(c) * (2 ** i) for i, c in enumerate(s[::-1]))
This reverses the string (s[::-1]
), gets each character c
and its index i
(for i, c in enumerate(
), multiplies the integer of the character (int(c)
) by two to the power of the index (2 ** i
) then adds them all together (sum()
).
Admin
Updated on January 28, 2022Comments
-
Admin over 2 years
I need to convert a binary input into a decimal integer. I know how to go from a decimal to a binary:
n = int(raw_input('enter a number: ')) print '{0:b}'.format(n)
I need to go in the reverse direction. My professor said that when he checks our code, he is going to input
11001
, and he should get25
back. I've looked through our notes, and I cannot figure out how to do this. Google and other internet resources haven't been much help either.The biggest problem is that we are not allowed to use built-in functions. I understand why we are not allowed to use them, but it's making this problem much more difficult, since I know Python has a built-in function for binary to decimal.