Binary to Decimal Converter Challenge

Binary to Decimal Converter Challenge

Python Coding Challenge

 

The objective of this Python coding challenge is to write a Python program that converts binary numbers to decimal numbers without using Python built-in functions. When the program is executed, it should display two columns: one with the binary numbers and another with their equivalent decimal numbers. The program should convert binary numbers from 10 to 20. Ensure that you implement the formula to convert binary to decimal:

N = bn*q^n + bn-1*q^n-1 + …,

where bn is the binary digit at position n and q is the base. Remember to adhere to the provided formula and avoid using any built-in functions for conversion.

The binary numbers from 10 to 20 are:

1010, 1011, 1100, 1101, 1110, 1111, 10000, 10001, 10010, 10011, 10100

Guide

The steps to complete this Python coding challenge:

  1. Define the Binary Numbers and Exponent:
    • Define a list of binary numbers from 1010 to 10100.
    • Define the base (q) as 2.
  2. Convert Binary to Decimal:
    • Iterate through the list of binary numbers and calculate the equivalent decimal representation using the provided formula N = bnq^n + bn-1q^n-1 + …
  3. Display the Conversion:
    • Print the binary numbers and their equivalent decimal numbers in two columns.

Expected output

Binary   |   Decimal
--------------------
1010   |   10
1011   |   11
1100   |   12
1101   |   13
1110   |   14
1111   |   15
10000   |   16
10001   |   17
10010   |   18
10011   |   19
10100   |   20

 

SOLUTION

# Define the list of binary numbers and the base
binary_numbers = ['1010', '1011', '1100', '1101', '1110', '1111', '10000', '10001', '10010', '10011', '10100']
base = 2

# Convert binary to decimal using the provided formula
print("Binary   |   Decimal")
print("--------------------")
for binary in binary_numbers:
    decimal = 0
    exponent = len(binary) - 1
    for digit in binary:
        decimal += int(digit) * (base ** exponent)
        exponent -= 1
    print(f"{binary}   |   {decimal}")

More Python challenges here!

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for Practice
Register New Account
Shopping cart