39

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.

purlinka
  • 399
  • 1
  • 3
  • 4
  • Check [this](https://stackoverflow.com/questions/35450560/how-to-use-python-to-convert-an-octal-to-a-decimal/47823029#47823029) out. The answer from Grace L. Samson might be useful –  Dec 14 '17 at 23:11

8 Answers8

91

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
>>>
  • 1
    something tells me his prof wants him to write the converter himself rather then using an existing function. Upvote for an elegant solution though – OutFall Feb 13 '14 at 21:26
  • Exactly what N0ir said. I edited the post to clarify that. Otherwise, this problem would be much easier. – purlinka Feb 13 '14 at 21:39
  • @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) – purlinka Feb 13 '14 at 21:55
  • @purlinka - 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. –  Feb 13 '14 at 22:01
  • works great, verified using the online number convertor here - https://randomtools.io/binary-to-decimal/ – user2475624 Apr 30 '22 at 10:31
33

Binary to Decimal

int(binaryString, 2)

Decimal to Binary

format(decimal ,"b")
cegprakash
  • 2,937
  • 33
  • 60
  • 5
    Python has [bin()](https://docs.python.org/3/library/functions.html#bin) function to convert decimal to binary string. `bin(26) => # '0b11010'` that was introduced in Python 2.6. – CodeMonkey Jul 21 '21 at 18:07
  • @CodeMonkey: +1 for shorter code but it has a 0b prefix in the resulting string which some might not want. – cegprakash May 23 '22 at 17:04
16

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

Anvar Kurmukov
  • 586
  • 3
  • 8
  • 6
    Have you ever considered that numpy arrays just are way faster than python lists? – univalence Dec 21 '20 at 12:10
  • 1
    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! – Anvar Kurmukov Dec 22 '20 at 05:22
  • Beautiful! Quibble: this is linear regression, not logistic regression, right? – Peter Drake Dec 23 '20 at 17:20
  • 4
    The interviewers face when I try to use this on a technical interview – marzano Aug 12 '21 at 06:43
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()).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
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!

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
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)
V. Gokul
  • 9
  • 1
  • Thanks for the working answer @V.Gokul, though can you add some explanation to it? It seems that the OP @purlinka struggles with the task in theory. Basically give an explanation on what is happening here: `res.append(ar[i]*(2**i))` Thanks! – tafaust Aug 23 '18 at 06:31
  • 1
    It will multiply the each digits of binary numbers with their respective 2**i values For e.g 0010 -> 0100 on ar[::-1] and ((0)*(2**0))+((1)*(2**1))+.. – V. Gokul Aug 23 '18 at 09:07
  • 1
    You should ***[edit]*** that to the answer itself, not post as a comment – Tomerikoo Dec 11 '21 at 08:27
-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)))

Bernhard Wagner
  • 1,681
  • 12
  • 15