python实现进制转换

# -*-coding:utf-8 -*-
# 支持整数、小数的进制转换,但只限于10,2,8,16之间


def deciaml_to(num_str, to_base, precision=4):
    num_str_inte = ''
    num_str_deci = ''
    if '.' in num_str:
        num_str_inte = num_str.split('.')[0]
        num_str_deci = num_str.split('.')[-1]
    else:
        num_str_inte = num_str
    num = int(num_str_inte)
    base = int(to_base)
    result_inte = []
    result_deci = []
    while num:
        remainder = num % base
        num /= base
        result_inte.append(str(remainder))
    if num_str_deci:
        num = float('0.' + num_str_deci)
        for i in range(int(precision)):
            num *= base
            t = int(num)
            result_deci.append(str(t))
            num -= t
    result_inte.reverse()
    result = result_inte + ['.'] + result_deci
    print result
    if to_base == '16':
        res = []
        for i in result:
            if i != '.':
                if int(i) >= int('10'):
                    i = chr(int(i) - 10 + ord('a'))
            res.append(i)
        return ''.join(res)
    else:
        return ''.join(result)


def to_decimal(num_str, from_base):
    s = []
    res1 = 0
    res2 = 0
    num_str_inte = ''
    num_str_deci = ''
    base = int(from_base)
    for i in num_str:
        if i.isalpha():
            s.append(str(ord(i) - ord('a') + 10))
        else:
            s.append(i)
    if '.' in s:
        n = s.index('.')
        num_str_inte = s[:n]
        num_str_deci = s[n + 1:]
    else:
        num_str_inte = s
    for i in range(len(num_str_inte)):
        res1 += int(num_str_inte[i]) * (base**(len(num_str_inte) - 1 - i))
    for i in range(len(num_str_deci)):
        res2 += int(num_str_deci[i]) * (base**(-i - 1))
    return str(res1 + res2)


if __name__ == '__main__':
    print "[功能]:支持整数、小数的进制转换,但只限于 10,2,8,16之间"
    num_str = raw_input('[num]:')
    from_base = raw_input('[from_base]:')
    to_base = raw_input('[to_base]:')
    if from_base == '10':
        precision = raw_input('[precision]:')
        print deciaml_to(num_str, to_base, precision)
    elif to_base == '10':
        print to_decimal(num_str, from_base)
    else:
        precision = raw_input('[precision]:')
        temp = to_decimal(num_str, from_base)
        print deciaml_to(temp, to_base, precision)

你可能感兴趣的:(python实现进制转换)