[python] 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.

This question is related to python python-2.7 binary integer base-conversion

The answer is


Try this solution:

def binary_int_to_decimal(binary):
    n = 0
    for d in binary:
        n = n * 2 + d

    return n

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!


Binary to Decimal

int(binaryString, 2)

Decimal to Binary

format(decimal ,"b")

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

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)

This is the full thing

binary = input('enter a number: ')
decimal = 0
for digit in binary:
decimal= decimal*2 + int(digit)

print (decimal)

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


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!


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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to binary

Difference between opening a file in binary vs text Remove 'b' character do in front of a string literal in Python 3 Save and retrieve image (binary) from SQL Server using Entity Framework 6 bad operand types for binary operator "&" java C++ - Decimal to binary converting Converting binary to decimal integer output How to convert string to binary? How to convert 'binary string' to normal string in Python3? Read and write to binary files in C? Convert to binary and keep leading zeros in Python

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to base-conversion

Converting binary to decimal integer output Converting an integer to a hexadecimal string in Ruby