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

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.

# This line initializes a string variable named binary_num to the value '1101',
# which is a binary number representation
binary_num = '1101'

# This line converts the binary number representation in the binary_num string to a decimal number
# The second parameter of the int function (base 2) indicates that the string represents a binary number
decimal_num = int(binary_num, 2)

# This line prints the decimal number that corresponds to the binary number in binary_num
print(decimal_num)

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

# Assign a binary number as a string to the variable 'bin_num'
bin_num = '1101'

# Initialize a variable 'deci_num' to 0 to store the decimal equivalent of the binary number
deci_num = 0

# Loop through each digit in the binary number using the range() function
for i in range(len(bin_num)):
    # Convert the digit at index i from a string to an integer
    digit = int(bin_num[i])
    
    # Calculate the decimal equivalent of the binary digit by multiplying it with 2 #raised to the power of the digit's position
    # The position of the digit is determined by subtracting the current index i from                #the length of the binary number and subtracting 1
    deci_num += digit * 2**(len(bin_num)-i-1)
    
# Print the final decimal equivalent of the binary number
print(deci_num)

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.
Output: 13

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.

# Import the 'reduce' function from the 'functools' module
from functools import reduce

# Assign a binary number as a string to the variable 'bin_num'
bin_num = '1111'

# Use the 'reduce' function to calculate the decimal equivalent of the binary number
# The 'reduce' function takes two arguments: a function and a list (or other iterable) # of values
# The function is applied cumulatively to the values in the list, from left to right
deci_num = reduce(lambda x, y: 2*x + y, [int(digit) for digit in bin_num])

# Print the final decimal equivalent of the binary number
print(deci_num)

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
Output: 15

Read How to convert Python Dictionary to a list

READ:  Palindrome Program using function in Python

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.

# Assigning a binary number to a string variable
bin_num = "10101"   

# Initializing a variable to hold the decimal value
deci_num = 0        

# Iterate over each digit in the binary string
for digit in bin_num:
    
    # Shifts the bits in `deci_num` one position to the left and then bitwise OR with the 
    # integer value of the current digit (0 or 1) to get the decimal equivalent of the binary number
    deci_num = (deci_num << 1) | int(digit) 

# Output the decimal equivalent of the binary number
print(deci_num)     

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.
Output: 21

Method-5:

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.

bin_num = "11101"    # Assigning a binary number to a string variable

# Calculate the decimal value of the binary number using a list comprehension
deci_num = sum([int(bin_num[i]) * 2**(len(bin_num)-i-1) for i in range(len(bin_num))])

# Output the decimal equivalent of the binary number
print(deci_num)

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.
Output: 29

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 defines a recursive function that converts a binary number represented as a string into its equivalent decimal representation.

def binary_to_decimal(binary_num):

    # Check if the binary number string contains only one digit
    if len(binary_num) == 1:
      # Return the integer value of the single digit binary number
        return int(binary_num)   

    # If the binary number string has more than one digit
    else:
        # Compute the decimal equivalent of the binary number by recursively calling the `binary_to_decimal()`
        # of the last character in the binary string.
        return int(binary_num[-1]) + 2 * binary_to_decimal(binary_num[:-1])

# Assigning a binary number to a string variable
binary_num = "10101"

# Convert the binary number to decimal by calling the `binary_to_decimal()` function
decimal_num = binary_to_decimal(binary_num)

# Output the decimal equivalent of the binary number
print(decimal_num)

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.
Output: 21

Another Example- Python program to convert binary to decimal using recursion

READ:  Python Split Regex

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:

# Defining the function
def BinaryToDecimal(num, expo=1):
    if num== 0:
        return 0
    else:
        digit= num % 10
        num= int(num / 10)
        digit= digit * expo
        return digit + BinaryToDecimal(num, expo * 2)
        
# Taking user input
num = int(input('Enter a binary number: '))

# Displaying Output
print('The decimal value is =', BinaryToDecimal(num))
  • 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. 20).
  • 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
Binary to decimal conversion 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.

# This code converts a binary number represented as a string into its equivalent decimal value using the built-in `eval()` function.

# Assigning a binary number to a string variable
binary_num = "10101"

# Convert the binary number to decimal using the `eval()` function, which evaluates # the binary string as a Python expression
# that represents an integer value in binary format.
decimal_num = eval("0b" + binary_num)

# Output the decimal equivalent of the binary number
print(decimal_num)

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.
Output: 21

Read Python Check if a variable is a number

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.

binary_num = int(input("Enter the Binary Number: "))
dec_num = 0
m = 1
length = len(str(binary_num))

for k in range(length):
    reminder = binary_num % 10
    dec_num = dec_num + (reminder * m)
    m = m * 2
    binary_num = int(binary_num/10)

print("Equivalent Decimal Value = ", dec_num)

Let me explain some parts of the program.

  • dec_num is the decimal number that we will get as a result. Initially, it’s value is zero.
  • The m variable inside the loop is the value of exponential term of 2 after every loop.
  • We are multiplying every digit of the binary number to the value of m.
  • Finally, adding all the values after multiplication with the susequent powers of 2, we will get our final result.
Binary to decimal in Python without inbuilt function
Binary number to decimal conversion

Thus, you might have learned how to convert a binary number into a decimal number without using any inbuilt function in Python.

There are some other alternative methods also. You will find them in the upcoming sections.

Also, check Python 3 string methods with examples

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

In the above section, we converted a binary number data type into a decimal in Python. This time, we will convert a binary string into a decimal i.e. the input will be a string.

binary_num = input("Enter the Binary Number: ")
dec_num = 0
m = 1

for digit in binary_num:
    digit= int(digit)
    dec_num = dec_num + (digit * m)
    m = m * 2

print("Equivalent Decimal Value = ", dec_num)
  • In the above program, we are taking the binary string input and iterating over it using the for loop.
  • Inside the loop, we are converting every binary character into an integer data type.
  • After that, we are multiplying the binary digit with the subsequent terms of 2’s exponent values.
  • In the end, we are adding the resulting values and storing inside a variable.
Binary string to decimal in Python without inbuilt function
Binary string to decimal conversion

Thus, you might have learned how to convert a binary string into a decimal without using any in-built functions in Python.

READ:  6 Ways to Save image to file in Python

Read Python compare strings

Method-10: Python program to convert binary to decimal using while loop

In this section, you will see a Python program to convert a binary number into a decimal number using the while loop. The Python program is written below:

def BinaryToDecimal(num):
    expo =1
    dec_num= 0
    while(num):
        digit = num % 10
        num = int(num / 10)
        
        dec_num += digit * expo
        expo = expo * 2
    return dec_num

# Taking user input
num = int(input('Enter a binary number: '))

# Displaying Output
print('The decimal value is =', BinaryToDecimal(num))
  • 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
Binary to decimal conversion using the while loop

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

Read Python find substring in string

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 * 23 + 0 * 22 + 1 * 21 + 1 * 20,

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.

def binToDeci():
    binary_num = input('Enter a binary string:')
    dec_num = int(binary_num, 2)
    return dec_num

def deciToBin():
    dec_num = int(input('Enter a decimal number:'))
    binary_num= bin(dec_num).replace('0b', '')
    return binary_num

print('''Enter 1 for Binary to decimal conversion
Enter 2 for Decimal to Binary conversion ''')
choice = int(input('Enter your choice: '))

if choice == 1:
    print('Decimal conversion of the binary number is:', binToDeci())
elif choice == 2:
    print('Binary represntation of the decimal number is:', deciToBin())
else:
    print('Invalid Choice')
Python program to convert decimal to binary and vice versa
Output in call test cases

Using this Python program, you can convert any decimal number into a binary number and vice-versa.

Read Convert float to int Python + Examples

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.

def binToDeci(binary_num):
    dec_num = int(binary_num, 2)
    return dec_num

def binToOct(binary_num):
    dec_num = int(binary_num, 2)
    oct_num= oct(dec_num)
    return oct_num

def binToHex(binary_num):
    dec_num = int(binary_num, 2)
    hex_num= hex(dec_num)
    return hex_num

binary_num = input('Enter a binary string:')
print('Decimal representation of the binary number is:', binToDeci(binary_num))
print('Octal representation of the binary number is:', binToOct(binary_num))
print('Hexadecimal representation of the binary number is:', binToHex(binary_num))
Python program to convert binary to decimal octal and hexadecimal
Converting binary to various number systems

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:

def binToDeci(binary_num):
    dec_num = int(binary_num, 2)
    return dec_num

def binToOct(binary_num):
    dec_num = int(binary_num, 2)
    oct_num= oct(dec_num).replace('0o', '')
    return oct_num

def binToHex(binary_num):
    dec_num = int(binary_num, 2)
    hex_num= hex(dec_num).replace('0x', '')
    return hex_num

binary_num = input('Enter a binary string:')
print('Decimal representation of the binary number is:', binToDeci(binary_num))
print('Octal representation of the binary number is:', binToOct(binary_num))
print('Hexadecimal representation of the binary number is:', binToHex(binary_num))
Python program to convert binary to decimal octal and hexadecimal
Output using the replace() function

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