purlinka
purlinka

Reputation: 469

Converting binary to decimal integer output

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 get 25 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.

Upvotes: 46

Views: 254649

Answers (9)

Ammar
Ammar

Reputation: 192

This is one of the most efficient way with complexity equals to the O(length of digit):

binary = input("Enter a binary no.")
decimal = 0
for digit in binary:
    decimal = decimal * 2 + int(digit)
print(decimal)

Here, you don't need to reverse your binary string.

Upvotes: -1

Anvar Kurmukov
Anvar Kurmukov

Reputation: 662

There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:

  1. Train an AI algorithm to convert 32-binary number to decimal based.
  2. 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(fit_intercept=False)
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:

enter image description here

This AI solution converts numbers almost x10 times faster than conventional way!

upd. seems like LinearRegression started using fit_intercept=True by default at some point, hence the edit.

Upvotes: 16

cegprakash
cegprakash

Reputation: 3125

Binary to Decimal

int(binaryString, 2)

Decimal to Binary

format(decimal ,"b")

ps: I understand that the author doesn't want a built-in function. But this question comes up on the google feed even for those who are okay with in-built function.

Upvotes: 36

Bernhard Wagner
Bernhard Wagner

Reputation: 1842

Using the power (**) function is a bit of a waste, so @user2555451's solution really is the way to go (Horner's method). Here's a fancy variation on it (less efficient, though, since the string needs to be reversed. The str-cast is there to allow for integers to be passed as well):

from itertools import accumulate, repeat
from operator import mul

def bin2dec(bin_str):
    return sum(
        int(n) * m for n, m in zip(
            str(bin_str)[::-1],
            accumulate((repeat(2)), func=mul, initial=1)))

Upvotes: -2

V. Gokul
V. Gokul

Reputation: 7

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)

Upvotes: -1

M. kavin babu
M. kavin babu

Reputation: 37

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

Upvotes: -1

MrSheng
MrSheng

Reputation: 1

I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

def __degree(number):
    power = 1

    while number % (10**power) != number:
        power += 1

    return power

def __getDigits(number):
    digits = []
    degree = __degree(number)

    for x in range(0, degree):
        digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
    return digits

def binaryToDecimal(number):
    list = __getDigits(number)
    decimalValue = 0
    for x in range(0, len(list)):
        if (list[x] is 1):
            decimalValue += 2**(len(list) - x - 1)
    return decimalValue

Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

binaryNum = int(input("Enter a binary number: "))

print(binaryToDecimal(binaryNum))

This prints out the correct result. Cheers!

Upvotes: -1

user2555451
user2555451

Reputation:

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
>>>

Upvotes: 104

jonrsharpe
jonrsharpe

Reputation: 122143

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()).

Upvotes: 2

Related Questions