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:
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.
8 Answers 8
You can use int and set the base to 2 (for binary):
However, if you cannot use int like that, then you could always do this:
Below is a demonstration:
Binary to Decimal
Decimal to Binary
There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:
- Train an AI algorithm to convert 32-binary number to decimal based.
- Predict a decimal representation from 32-binary.
See example and time comparison below:
This AI solution converts numbers almost x10 times faster than conventional way!
![]()
If you want/need to do it without int :
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:
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:
Преобразование типов#
В Python есть несколько полезных встроенных функций, которые позволяют преобразовать данные из одного типа в другой.
int преобразует строку в int:
С помощью функции int можно преобразовать и число в двоичной записи в десятичную (двоичная запись должна быть в виде строки)
Преобразовать десятичное число в двоичный формат можно с помощью bin :
Аналогичная функция есть и для преобразования в шестнадцатеричный формат:
Функция list преобразует аргумент в список:
Функция set преобразует аргумент в множество:
Эта функция очень полезна, когда нужно получить уникальные элементы в последовательности.
tuple #
Функция tuple преобразует аргумент в кортеж:
Это может пригодиться в том случае, если нужно получить неизменяемый объект.
Перевод чисел в Python
В данном материале мы рассмотрим встроенные возможности по переводу чисел в языке программирования Python, а также напишем универсальную функцию по их переводу.
Перевод чисел из десятичной системы счисления
Для перевода числа из десятичной системы счисления в двоичную можно воспользоваться оператором bin(). В качестве аргумента нужно передать значение в виде числа, а оператор вернет строку с двоичным числом. У результата также будет префикс 0b, указывающий на основание системы счисления.
| Python | Вывод |
|---|
Для перевода в восьмеричную систему счисления есть оператор oct(). Он также возвращает строку с восьмеричным числом и префиксом 0o.
| Python | Вывод |
|---|
При переводе в шестнадцатеричную систему счисления воспользуемся оператором hex(). Он вернет строку шестнадцатеричным числом и префиксом 0x
| Python | Вывод |
|---|
Если же вам не нужен префикс у результата перевода, то всегда можно взять срез у полученной строки.
| Python | Вывод |
|---|
А теперь напишем универсальную функцию convert_to() по переводу чисел из десятичной системы счисления в систему счисления в любым основанием. Наша функция будет ограничена только наличием символов в переводимой системе счисления.
Данная функция принимает три аргумента, два из которых обязательные. Это десятичное целое число number и основание переводимой системы счисления base. Третий аргумент upper служит для указания регистра вывода строки переведенного числа. По умолчанию он установлен в значение False.
Во второй строке мы задаем переменную digits, содержащую набор символов цифр и букв английского языка. Она нам понадобится для составления символов переведенного числа на основании остатков.
В третьей строке мы проверяем основание переданной системы счисления на его длину. Если основание окажется больше, чем количество символов в нашей строке digits, то мы прекращаем выполнение функции через вызов оператора return и возвращаем None. Это такая своеобразная защита функции от неправильно переданных аргументов. Если мы попробуем перевести число в большую систему счисления по основанию, чем у нас есть символов для его записи, то мы его не сможем записать.
Дальше заведем переменную result для хранения результата работы функции и зададим ей значение в виде пустой строки. Теперь с помощью цикла с условием будем находить остаток от деления числа number на основание base, а также уменьшать number в base раз используя целочисленное деление.
Остаток от деления числа на основание переводимой системы счисления мы будем использовать как индекс для получения символа в строке digits и добавлять его к результату result. Добавлять это значение следует слева, т.к. самый первый остаток является самым правым разрядом. Цикл выполняется до тех пор, пока исходное значение переменной number больше нуля.
После завершения цикла мы вернем результат через вызов return. Для этого воспользуемся тернарным оператором и проверим наш третий аргумент. Если он будет в значении True, то для строки result вызовем строкой метод .upper() который заменит все прописные символы английского языка на строчные. Иначе, вернем результат как есть.
А теперь проверим работу нашей функции. Для этого попробуем перевести числа в 2ю, 8ю, 16ю, 32ю и 64ю системы счисления. Для перевода в 32ю систему счисления мы укажем третий необязательный аргумент upper и зададим ему значение True.
| Python | Вывод |
|---|
Перевод чисел в десятичную систему счисления
Для обратного перевода в десятичную систему счисления мы будем использовать оператор int(). Для этого передадим ему два аргумента, первый — это строка с числом в какой-то системе счисления, а второй — это основание системы счисления самого числа. По умолчанию для этого необязательного аргумента стоит значение равное 10.
В качестве самого числа нужно обязательно передать строку. Строка может содержать или само число или число с префиксом системы счисления.
Для перевода из двоичной системы счисления:
| Python | Вывод |
|---|
| Python | Вывод |
|---|
Для перевода из восьмеричной системы счисления:
| Python | Вывод |
|---|
| Python | Вывод |
|---|
И для перевода из шестнадцатеричной системы счисления:
| Python | Вывод |
|---|
| Python | Вывод |
|---|
В качестве второго аргумента мы можем передавать любое число в диапазоне от 2х до 36 включительно. Тем самым переводя число из любой системы счисления в десятичную.
Python convert binary to decimal + 15 Examples
In this Python tutorial, we will learn various ways to convert a binary number into a decimal number in Python. We will discuss some in-built methods as well as create our own methods for converting a binary string into a decimal.
- How to convert binary string to decimal in Python
- Python program to convert binary to integer
- Python convert binary to float
- Python program to convert binary to octal
- Binary to decimal in Python without inbuilt function
- Binary string to decimal in Python without inbuilt function
- Python program to convert binary to decimal using while loop
- Python program to convert binary to decimal using recursion
- Python program to convert binary to hexadecimal
- Python program to convert binary to hexadecimal using while loop
- Python program to convert binary to ASCII
- Convert binary list to decimal Python
- Python program to convert decimal to binary and vice versa
- Python program to convert binary to decimal octal and hexadecimal
Table of Contents
How to convert binary string to decimal in Python
Let us understand the logic behind this conversion with the help of an example.
Consider the binary number: 1011
Now we will multiply every single digit with the multiples of 2 starting from the unit’s place. Then we will add all the resulting values. The calculation will be like this:
Decimal number= 1 * 2 3 + 0 * 2 2 + 1 * 2 1 + 1 * 2 0 ,
which is equivalent to 8 + 0 + 2 + 1 = 11
You can convert a binary string into a decimal in Python in various ways. You can use either the int() or the float() functions to convert a binary string into an integer or a float number respectively.
Another way is to use our own logic to create a Python program. We will use the logic that we saw in the above explanation.
Python program to convert binary to integer
First of all, let us convert a binary string into an integer using the int() function in Python. the following is a simple Python program to convert a binary string into an integer:
- In the above program, we are taking a string input. This string number is supposed to be a binary number.
- Secondly, we are using the int() function and passing the binary string to this function.
- The second argument i.e 2 is representing that we are converting a binary number. Let us see the output now.

- You can see that the number is converted into a decimal and the data type is int i.e an integer.
In this way, you can convert a binary string into an integer using an in-built function.
Python convert binary to float
Let us see a Python program to convert a binary string into a float number. We will use the float() method in this example.
- You cannot use the float() function to directy convert a binary string into a float value. We can use the int() function to convert a binary string into an integer and then use the float() function to chnage the data type into float.

Python program to convert binary to octal
There are multiple ways to convert a binary number into an octal. I will demonstrate various examples of this type of conversion.
Example 1: Taking binary string input and use the in-built functions for conversion

This is the simplest method for converting a binary string into an octal number. Let us see another example.
Example 2: Taking a binary number and using our own logic for conversion.
In Python, If you want to convert a binary number into an octal, you have to convert the binary into a decimal first, and then convert this decimal number into an octal number.
- In the above Python program, we have created a function that will convert a binary number into a decimal number using a while loop.
- Then, we are taking the user input and pasing this input to the function while displaying result through the print statement.
- Let us give a sample input and check our program.

Hence, in this way, you can use the while loop in Python to convert a binary number to decimal.
Python program to convert binary to decimal using recursion
You can also use the recursion technique to convert a binary number into a decimal in Python. I will demonstrate this with an example.
Recursion is a technique in which a function calls itself inside its body for a particular condition. If the condition is satisfied it will call itself. Otherwise, the program will terminate.
The following is a Python program to convert a binary number into a decimal using the recursion method:
- In the above program, we have defined a function that takes two arguments i.e a binary number and the exponential value of 2.
- Initially, the exponential value will be 1 (i.e. 2 0 ).
- We have specified a condition that the function will not call itself again if it has become zero.
- Then, we will separate the last digit of the binary number, mulitply it with the current exponential term of 2 and return its sum with the recursively called function.
- This time, we will pass the binary number without the last digit with the next exponenetial term of 2 to the called function.

In simple words, every time this function will return a decimal digit, and at the end of all executions, these decimal digits will be added and we will get the calculated decimal number.
Python program to convert binary to hexadecimal
In this section, you will learn to convert a binary number into a hexadecimal number in Python.
Firstly, you have to convert the binary number into a decimal number. Then you can convert this decimal number into a hexadecimal number.
You can use the in-built functions to simply convert a binary number into a hexadecimal number. Below is the Python code snippet that you can use.

Hence, in this way you can convert a binary number into a decimal number in Python.
Python program to convert binary to hexadecimal using while loop
In this example, I will use a user-defined function to convert a binary input to hexadecimal using a while loop in Python.
The approach is the same as we discussed above for the conversion of binary numbers into octal. Firstly, we will convert the binary number into decimal and then convert this decimal number into hexadecimal.
We will define a list of hexadecimal characters and map the remainders with this list after every iteration while converting from decimal to hexadecimal.
![]()
In this way, you can convert a binary number into hexadecimal using the while loop in Python.
Python program to convert binary to ASCII
In this section, you will learn about various conversions related to binary and ASCII values in Python. I will explain some examples where you will learn various use cases of these types of conversions.
Suppose you have a binary of a string and you want to convert it to the ASCII values. Let us create a binary of a string first using a Python program.
The above code will create a binary string of our message with a space character between every binary string of a particular alphabetical character. The resultant binary string will be:
Now let us convert these binary strings to their corresponding ASCII values.
![]()
We are using the int() function to convert the binary values into their corresponding ASCII values.
Hence, in this way, you can convert a binary string into ASCII in Python.
Convert binary list to decimal Python
In this section. I will explain an example in which I will create a list of binary numbers and convert them into decimals in Python. Look at the code below:

Also, if you have a list containing binary decimals with the integer data type, you have to convert the elements into string data types. For example:
In the above example, you can see that the elements in the list are of integer data type. Therefore, we had to convert them into a string before converting them into decimal.

Thus, you might have learned how you can convert a binary list into decimals in Python.
Python program to convert decimal to binary and vice versa
Let us now create a Python program that will convert a decimal number into a binary number as well as convert the binary number to a decimal number.
I will be using the in-built functions for conversions. The int() function can be used to convert a binary string into a decimal while the bin() function can be used to convert the decimal number into binary.

Using this Python program, you can convert any decimal number into a binary number and vice-versa.
Python program to convert binary to decimal octal and hexadecimal
In this section, you will see a Python program, that will take a binary number as the user input and return the equivalent decimal, octal and hexadecimal number.

The 0o before the number represents that the number is octal and the 0x represents that the number is hexadecimal. if you do not want them with your output, you can use the replace() function as follows:

You may like the following Python tutorials:
In this way, you can create a Python program that converts a binary number into decimal, octal, and hexadecimal numbers.
- How to convert binary string to decimal in Python
- Python program to convert binary to integer
- Python convert binary to float
- Python program to convert binary to octal
- Binary to decimal in Python without inbuilt function
- Binary string to decimal in Python without inbuilt function
- Python program to convert binary to decimal using while loop
- Python program to convert binary to decimal using recursion
- Python program to convert binary to hexadecimal
- Python program to convert binary to hexadecimal using while loop
- Python program to convert binary to ASCII
- Convert binary list to decimal Python
- Python program to convert decimal to binary and vice versa
- Python program to convert binary to decimal octal and hexadecimal

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.