Как перевести из двоичной в десятичную в python
Перейти к содержимому

Как перевести из двоичной в десятичную в python

  • автор:

Преобразование типов#

В Python есть несколько полезных встроенных функций, которые позволяют преобразовать данные из одного типа в другой.

int преобразует строку в int:

С помощью функции int можно преобразовать и число в двоичной записи в десятичную (двоичная запись должна быть в виде строки)

Преобразовать десятичное число в двоичный формат можно с помощью bin :

Аналогичная функция есть и для преобразования в шестнадцатеричный формат:

Функция list преобразует аргумент в список:

Функция set преобразует аргумент в множество:

Эта функция очень полезна, когда нужно получить уникальные элементы в последовательности.

tuple #

Функция tuple преобразует аргумент в кортеж:

Это может пригодиться в том случае, если нужно получить неизменяемый объект.

How to Convert a Number from Binary to Decimal in Python

Claudio Sabato

Would you like to learn how to convert a number from binary to decimal in Python? You are in the right place.

In Python, you represent binary numbers using 0b followed by the number. To convert a binary number to a decimal number Python provides the int() function. To convert the other way around, from decimal to binary, Python provides the bin() built-in function.

Claudio Sabato

Written by Claudio Sabato

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Из двоичной в десятичную

Эта функция преобразует двоичные числа в десятичные. Как она работает.

insolor's user avatar

Artem Zaecev's user avatar

вася's user avatar

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.8.43486

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Convert Binary to Decimal in Python [10 Different Methods]

In this Python tutorial, we will learn, how to convert binary to decimal in Python. There are various ways to convert binary to decimal 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
  • 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 decimal to binary and vice versa
  • Python program to convert binary to decimal octal and hexadecimal

Table of Contents

How to Convert Binary to Decimal in Python

There are different ways, we can convert binary to decimal in Python.

Method-1: Convert binary to decimal in Python using int()

The easiest way to convert a binary number to decimal in Python is to use the built-in int() function with a base parameter of 2.

The above code converts a binary number (in the form of a string) to its decimal equivalent and prints it to the console.

Convert binary to decimal in python using the int

Method-2: Convert binary to decimal in Python using for loop

Another way to convert a binary number to decimal in python is to use a for loop to iterate over each digit in the binary number, starting from the rightmost digit, and calculate the decimal equivalent.

The above code converts a binary number (represented as a string) into its decimal equivalent.

  • It does this by looping through each digit in the binary number, converting it to an integer, and then multiplying it by 2 raised to the power of its position in the number.
  • The decimal equivalents of each digit are then added together to produce the final decimal equivalent of the binary number, which is stored in the variable deci_num.

Method-3: Convert binary to decimal in Python using reduce() function

The python reduce() function from the functools module can also be used to convert a binary number to decimal by iteratively applying a function to a sequence of values. In this case, we can use reduce() to calculate the decimal equivalent of each binary digit.

The above code converts a binary number (represented as a string) into its decimal equivalent using the reduce() function from the functools module.

  • The lambda function passed to reduce() takes two arguments, x and y , and returns the result of doubling x and adding y to it.
  • The reduce() function applies this lambda function cumulatively to the list of binary digits (converted to integers using a list comprehension), starting from the left.
  • The final result of the reduce() function is the decimal equivalent of the binary number, which is stored in the variable deci_num. Finally, the code prints the value of d

Method-4: Convert binary to decimal in Python using the bitwise shift operator

This method involves iterating through each bit in the binary number and using the bitwise shift operator to calculate the decimal value. We shift the decimal number to the left by one bit and then add the next bit from the binary number to it.

The above code takes a binary number represented as a string and converts it to its equivalent decimal value using bit manipulation.

  • It initializes a variable to hold the decimal value and then iterates through each digit of the binary number string.
  • For each digit, it shifts the bits of the decimal value one position to the left and then bitwise OR with the integer value of the current digit to get the decimal equivalent of the binary number.
  • Finally, it outputs the decimal equivalent of the binary number.

Method-5: Convert binary to decimal in Python using the sum() function and a list comprehension

This method involves using the sum() function and a list comprehension to iterate through each bit in the binary number and calculate its decimal value.

The above code converts a binary number represented as a string to its equivalent decimal value using list comprehension.

  • It iterates over each digit in the binary string and computes the value of that digit multiplied by the corresponding power of 2, based on the position of the digit in the string.
  • The list comprehension creates a list of these values, which are then summed to get the decimal equivalent of the binary number.
  • The resulting decimal value is output using the print() function.

Method-6: Convert binary to decimal in Python using recursion

This method involves using recursion to convert a binary number to a decimal in Python. We start by converting the rightmost bit to decimal, then multiply by 2 and add the decimal value of the remaining bits.

This code uses a recursive function to convert a binary number string to its decimal equivalent.

  • The function multiplies each digit in the binary string by its corresponding power of 2 and recursively adds them up to compute the decimal equivalent. The resulting decimal value is output using the print() function.

Another Example- 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.

Python program to convert binary to decimal using recursion

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.

Method-7: Convert binary to decimal in Python using the eval() function

In Python, we can also use the eval() function to convert binary to decimal.

This method involves using the eval() function to evaluate the binary number as a string of Python code that calculates its decimal value.

The above code first assigns a binary number to a variable binary_num.

  • Then, it converts the binary number to a decimal using the built-in eval() function. The eval() function evaluates the binary string as a Python expression that represents an integer value in binary format.
  • In this code, the eval() function is passed a string “0b” + binary_num as its argument, which appends the prefix “0b” to the binary string to indicate that it should be interpreted as a binary number.
  • The resulting decimal value is assigned to a variable decimal_num, which is then output using the print() function.

Method-8: Convert Binary to decimal in Python without inbuilt function

In this section, you will learn how to convert a binary string into a decimal without using any in-built function in Python. We will implement our own logic to perform this task. Look at the following Python program.

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

Python program to convert binary to decimal using while loop

Hence, in this way, you can use the while loop in Python to convert a binary number to decimal.

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

Python program to convert decimal to binary and vice versa

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.

Python program to convert binary to decimal octal and hexadecimal

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:

Python program to convert binary to decimal octal and hexadecimal

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
  • 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 decimal to binary and vice versa
  • Python program to convert binary to decimal octal and hexadecimal

Fewlines4Biju Bijay

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *