The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n): decimal = d0×20 + d1×21 + d2×22 + ...
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
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
>>>
Binary to Decimal
int(binaryString, 2)
Decimal to Binary
format(decimal ,"b")
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!
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With