在Python中将基数6转换为十进制,反之亦然? [英] Converting base 6 to decimal and vice versa in Python?

查看:94
本文介绍了在Python中将基数6转换为十进制,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数字从十进制转换为以6为底的数字,反之亦然,但是它不起作用.看来我并没有弄清楚该算法是否可以正常工作.有人可以向我解释如何在Python中实现它吗?

I'm trying to convert a number from decimal to base 6 and vice versa, but it's not working. It seems that I'm not figuring out the algorithm to get it to work. Could someone please explain to me how to implement it in Python?

这里是一个链接(单击此处),该链接提供了有关如何做到这一点,但是当我尝试使用while循环在Python中制作它时,却无法正常工作,结果变成了无限循环.最后,我不明白如何将所有余数加在一起形成最终值.

Here is a link(Click here) which gives an explanation on how to do it, but when I try to make it in Python using a while loop, but it's not working and turning out to be an infinite loop. And finally, I don't understand how I will append all the remainders together to form the final value.

谢谢

推荐答案

我希望这会对您有所帮助

i hope this will help you more

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

这篇关于在Python中将基数6转换为十进制,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆