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?
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.
Thanks
解决方案
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
the output is:
210 78