【问题标题】:Converting base 6 to decimal and vice versa in Python? [closed]在 Python 中将基数 6 转换为十进制,反之亦然? [关闭]
【发布时间】:2014-04-04 07:03:31
【问题描述】:

我正在尝试将数字从十进制转换为以 6 为基数,反之亦然,但它不起作用。似乎我没有弄清楚让它工作的算法。有人可以向我解释一下如何在 Python 中实现它吗?

这是一个链接(Click here),它解释了如何做到这一点,但是当我尝试在 Python 中使用 while 循环来实现它时,它不起作用并且变成了一个无限循环。最后,我不明白如何将所有余数附加在一起以形成最终值。

谢谢

【问题讨论】:

    标签: python decimal base


    【解决方案1】:

    希望对你有更多帮助

    def dec2hex(num):
        if num == 0:
            return 0
        ans = ""
        while num > 0:
            ans = str(num%6) + ans
            num /= 6
        return int(ans)
    
    def hex2dec(num):
        if num == 0:
            return 0
        num = str(num)
        ans = int(num[0])
        for i in num[1:]:
            ans *= 6
            ans += int(i)
        return ans
    
    if __name__ == '__main__':
        a = dec2hex(78)
        b = hex2dec(a)
        print a, b
    

    输出是:

    210 78
    

    【讨论】:

    • 我不会为此使用名称 hex - 通常你会想到基数 16。
    【解决方案2】:

    一个方向很明确:

    >>> int('42', 6)
    26
    

    另一种方式 - 将数字转换为以 6 为基数的表示 - 更棘手。似乎没有办法用内置函数和没有循环来做到这一点。

    所以人们可以做类似的事情

    def str_base(val, base):
        res = ''
        while val > 0:
            res = str(val % base) + res
            # val /= base # only valid for Py2
            val //= base # for getting integer division
        if res: return res
        return '0'
    

    这给出了例如:

    >>> str_base(7,6)
    '11'
    

    到目前为止,它只适用于

    import string
    alphabet = string.digits + string.ascii_lowercase
    

    并在函数中使用它

    res = alphabet[val % base] + res
    

    它(可能)仍然不适用于负数。如果你需要这些,你必须再付出一点努力。

    【讨论】:

    • -glglgl 我在 str_base 函数中尝试 7,6 时得到这个:它太长了,但它是这样的:1.5e-3238e-3234.9e-3222.945 ...
    猜你喜欢
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多