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}\'.fo
There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:
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!
Binary to Decimal
int(binaryString, 2)
Decimal to Binary
format(decimal ,"b")
The input may be string or integer.
num = 1000 #or num = '1000'
sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))
# 8
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()
).
a = input('Enter a binary number : ')
ar = [int(i) for i in a]
ar = ar[::-1]
res = []
for i in range(len(ar)):
res.append(ar[i]*(2**i))
sum_res = sum(res)
print('Decimal Number is : ',sum_res)
You can use int and set the base to 2
(for binary):
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> int(binary, 2)
25
>>>
However, if you cannot use int
like that, then you could always do this:
binary = raw_input('enter a number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print decimal
Below is a demonstration:
>>> binary = raw_input('enter a number: ')
enter a number: 11001
>>> decimal = 0
>>> for digit in binary:
... decimal = decimal*2 + int(digit)
...
>>> print decimal
25
>>>