Converting binary to decimal integer output
Asked Answered
C

9

44

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.

Carabiniere answered 13/2, 2014 at 21:23 Comment(1)
Check this out. The answer from Grace L. Samson might be usefulInexpressible
D
99

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
>>>
Devries answered 13/2, 2014 at 21:24 Comment(5)
something tells me his prof wants him to write the converter himself rather then using an existing function. Upvote for an elegant solution thoughCorneous
Exactly what N0ir said. I edited the post to clarify that. Otherwise, this problem would be much easier.Carabiniere
@iCodez - I tried the code you added to your edited post. For some reason it's not working? Says it's invalid syntax. (Thanks for you're help, btw)Carabiniere
@Carabiniere - Huh, that is odd. The syntax of my code is fine. Did you copy it correctly? Also, remember that you cannot just copy/paste my demonstration into the interpreter. You need to run it as a normal script.Devries
works great, verified using the online number convertor here - randomtools.io/binary-to-decimalInvariable
M
34

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.

Mixup answered 11/12, 2019 at 16:15 Comment(2)
Python has bin() function to convert decimal to binary string. bin(26) => # '0b11010' that was introduced in Python 2.6.Ichthyornis
@CodeMonkey: +1 for shorter code but it has a 0b prefix in the resulting string which some might not want.Mixup
H
17

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.

Hyams answered 21/8, 2020 at 13:11 Comment(4)
Have you ever considered that numpy arrays just are way faster than python lists?Gabrielagabriele
Sure, you could do that using a conventional intelligence and the fact that dot products are amazingly fast in numpy, but think a moment, what if you now want to convert to a base-3 or even base-4 (!) notation? With regular approach you need to think of all these right coefficients and multipliers, while with AI it just do the job for you!Hyams
Beautiful! Quibble: this is linear regression, not logistic regression, right?Peculation
The interviewers face when I try to use this on a technical interviewDespond
T
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()).

Totipalmate answered 13/2, 2014 at 21:32 Comment(0)
C
0

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!

Carpic answered 20/3, 2015 at 11:21 Comment(0)
T
0

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
Tayyebeb answered 8/8, 2015 at 10:48 Comment(0)
P
0
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)
Protestant answered 23/8, 2018 at 5:56 Comment(3)
Thanks for the working answer @V.Gokul, though can you add some explanation to it? It seems that the OP @Carabiniere struggles with the task in theory. Basically give an explanation on what is happening here: res.append(ar[i]*(2**i)) Thanks!Prussian
It will multiply the each digits of binary numbers with their respective 2i values For e.g 0010 -> 0100 on ar[::-1] and ((0)*(20))+((1)*(2**1))+..Protestant
You should edit that to the answer itself, not post as a commentGhetto
R
0

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.

R answered 4/7, 2024 at 9:17 Comment(0)
R
-1

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

Regardant answered 27/1, 2022 at 15:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.