Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Chapter 4 (python), we developed an algorithm for converting from binary to d

ID: 3602000 • Letter: I

Question

In Chapter 4 (python), we developed an algorithm for converting from binary to decimal. You can generalize this algorithm to work for a representation in any base. Instead of using a power of 2, this time you use a power of

the base. Also, you use digits greater than 9, such as A...F, when they occur. Define a function named repToDecimal that expects two argu- ments, a string and an integer. The second argument should be the base. For example, repToDecimal(“10”, 8) returns 8, whereas repToDecimal(“10”, 16) returns 16. The function should use a lookup table to find the value of any digit. Make sure that this table (it is actually a dictionary) is initialized before the function is defined. For its keys, use the 10 decimal digits (all strings) and the letters A...F (all uppercase). The value stored with each key should be the integer that the digit represents. (The letter 'A' associates with the integer value 10, and so on.) The main loop of the function should convert each digit to uppercase, look up its value in the table, and use this value in the compu- tation. Include a main function that tests the conversion function with numbers in several bases.

Explanation / Answer

import sys

def convertToBase10(n, base):
    number = []
    negative = False

    # If n is a negative number (it's a string at this moment of the code)..
    # then replace the minus sign with a blank character to correctly convert string to int...
    # so the algorithm can continue.
    if n[0] == '-':
        n = n.replace('-', '')
        negative = True

    for i in n:
        number.append(int(i))

    number = number[::-1]
    if negative:
        for i in range(len(number)):
            number[i] = number[i] * -1
            number[i] = number[i] * (base ** i)
    else:
        for i in range(len(number)):
            number[i] = number[i] * (base ** i)

    return sum(number)


def main():
    num = str(input("Enter a number: "))
    base = int(input("Enter the base of number: "))

    if base == 0 :
        print("Cannot have bases of 0. Exiting... ")
        raise SystemExit

    print("You entered " + num + " in base " + str(base) + ". ")

    n = convertToBase10(num, base)

    print("Your number in decimal base is " + str(n) + ". ")


if __name__ == "__main__":
    main()