Yashaswini Ravi
Yashaswini Ravi

Reputation: 49

Getting wrong output while converting from given base to any base

Here i am trying to convert a number which is in string format from old base to given newbase.

i am getting output as 650: but i should get 650A, not sure where i am going wrong in the following piece of code.

number is the string to be converted from oldbase to newbase.

number='a126'
oldbase=12
newbase=14

#start writing your code here
import math

def base_encode(number, base):
    # sanitize inputs
    number = str(number).lower()
    print(number)
    base = int(base)

    # legal characters
    known_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
    value  = { ch:val for val,ch in enumerate(known_digits) if val<base }

    # handle negative values    
    if number[0]=='-':
        sign = -1
        number = number[1:]
    else:
        sign = 1

    # do conversion
    total = 0
    for d in number:
        try:
            total = total*base + value[d]
        except KeyError:
            if d in known_digits:
                raise ValueError("invalid digit '{0}' in base {1}".format(d, base))
            else:
                raise ValueError("value of digit {0} is unknown".format(d))

    return sign*total
def base10toN(num, base):
    """Change ``num'' to given base
    Upto base 36 is supported."""

    converted_string, modstring = "", ""
    currentnum = num
    if not 1 < base < 37:
        raise ValueError("base must be between 2 and 36")
    if not num:
        return '0'
    while currentnum:
        mod = currentnum % base
        currentnum = currentnum // base
        converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string
    return converted_string
print(base10toN(base_encode(number,oldbase),newbase))

Upvotes: 1

Views: 70

Answers (1)

Vijaya Varma Lanke
Vijaya Varma Lanke

Reputation: 611

Find the solution here

Replace this line

converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string

with

converted_string = chr(48 + mod + 7*(mod >= 10)) + converted_string

Thank you.... HAPPY CODING

Upvotes: 1

Related Questions