可以实现任意进制之间转换的程序

投稿:宋欣源(1400012408)

# -*- coding: utf-8 -*-

class BaseConversion:

    def __init__(self):
        self.bit_dict = {}
        for i in range(65, 91):
            self.bit_dict[chr(i)] = i - 55

        self.letter_dict = {}
        for i in range(65, 91):
            self.letter_dict[i - 55] = chr(i)

    def is_letter(self, char):
        return (ord(char) >= 65 and ord(char) <= 90)

    def to_base_10(self, from_base, num_string):
        l = len(num_string)
        result = 0
        for i in range(l):
            bit = num_string[l - i - 1]
            if self.is_letter(bit):
                result += (from_base ** i) * self.bit_dict[bit]
            else:
                result += (from_base ** i) * int(bit)
        return result

    def log(self, base, num):
        exp = 0
        while base ** exp <= num:
            exp += 1
        if base ** exp > num:
            return exp - 1
        else:
            return exp

    def from_base_10(self, to_base, num):

        if num < to_base:
            if num < 10:
                return str(num)
            else:
                return self.letter_dict[num]

        bit_list = []
        bit_nums = self.log(to_base, num) + 1
        for i in range(bit_nums):
            bit_power = bit_nums - 1 - i
            bit_value = num / (to_base ** bit_power)
            bit_list.append(bit_value)
            num -= bit_value * (to_base ** bit_power)

        s = ""
        for i in bit_list:
            if i < 10:
                s += str(i)
            else:
                s += self.letter_dict[i]

        return s

    def convert(self, from_base, target_base, num_string):
        """
        把一个数(字符串形式)从一个进制转换至另一个进制。
        :param from_base: 原进制
        :param target_base: 目标进制
        :param num_string: 带转换数字(字符串)
        :return: 转换后的字符串
        """
        return self.from_base_10(target_base, self.to_base_10(from_base, num_string))

## 测试
bc = BaseConversion()
print bc.convert(10, 33, "32")

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*