Binary numbers are numbers in the base-2 system; this means they are only expressed using two numbers, and . In binary, all the digits in a number represent a power of , with the right-most digit starting with . Computers usually operate using the binary number system.
On the other hand, decimal numbers are the standard numbers used globally and belong to the base-10 system. They include numbers, starting from .
Let’s see how we can convert binary numbers into decimal numbers in Python.
A simple algorithm to convert binary numbers into decimal is given below:
Create a variable to store the decimal number. Initiate this variable to
Start iterating over each digit of the binary number from the right-most digit.
For each digit multiply the value of the digit with
Add the result to the variable created earlier to store the decimal.
Repeat steps
Let’s implement the aforementioned algorithm in the code widget given below:
def binary_to_decimal_converter(binary):decimal = 0power = 0# Iterate over each digit of the binary number from right to leftfor digit in reversed(binary):# Convert the digit to an integerdigit_value = int(digit)# Add the value of the digit multiplied by 2 raised to the power of its positiondecimal += digit_value * (2 ** power)# Move to the next positionpower += 1return decimalbinary_number = "10101"print("Binary:", binary_number)print("Decimal:", binary_to_decimal_converter(binary_number))
In the function given above,
Lines 6–12: We use a for
loop to iterate over the binary number and convert it into decimal using the algorithm mentioned above.
Line 8: We convert the binary digit (
Line 10: We multiply the binary digit with decimal
.
Line 14: Return the converted number.
Python provides us with a built-in function to convert binary numbers into decimals in case we don't want to get into the hassle of creating our function. Let’s see how this function works in the code given below:
binary_number = "10101"decimal_number = int(binary_number, 2)print("Binary number:", binary_number)print("Decimal number:", decimal_number)
In the function given above, we use the function int()
to convert our binary number into decimal. In this function, we provide 2
as the input, which specifies the base for our input function.
Binary-to-decimal conversion is a fundamental and common algorithm used in computer science and digital electronics. We can convert a binary number into a decimal by multiplying each digit in the binary number with int()
, available in Python to convert binary numbers into decimal.
Free Resources