In this tutorial, we will learn how to convert binary numbers to decimal numbers in Python.
A binary number is a number represented in base 2, with each digit being either a 0 or a 1. A decimal number, on the other hand, is a number represented in base 10, with each digit being a number between 0 and 9.
Examples of converting Binary to Decimal in Python Using loops
def binaryTodecimal(binary):
decimal = 0
for i, digit in enumerate(binary[::-1]):
if digit == '1':
decimal += 2 ** i
return decimal
# test the function
print(bin_to_dec('1001')) # prints 9
print(bin_to_dec('1010')) # prints 10
print(bin_to_dec('11011')) # prints 27
Output:
9
10
27
You can use this function to convert any binary number to a decimal number in Python. Just pass the binary number as a string to the binaryTodecimal
function and it will return the corresponding decimal number
This function works by iterating through the digits of the binary number from least significant to most significant (right to left). For each digit that is a 1
, it adds 2 to the power of the digit’s position to the decimal number.
Approach
- Define a function called
binaryTodecimal
that takes a binary number as a string and returns the corresponding decimal number. - Initialize a variable called
decimal
0. This will store the decimal equivalent of the binary number. - Iterate through each digit in the binary number, from least significant to most significant (right to left).
- For each digit that is a 1, add 2 to the power of the digit’s position to the
decimal
variable. - Return the
decimal
variable as the result of the function.
Latest posts by Publisher (see all)
- pybase64 encode and decode Messages using Python - June 6, 2023
- Different Data Types in Dart - June 6, 2023
- What is flutter and dart and the difference - June 4, 2023