问题
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
回答1:
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
回答2:
One direction is clear:
>>> int('42', 6)
26
The other way - convert a number to a base 6 representation - is trickier. There seems to be no way to do it with built-in functions and without a loop.
So one could do something like
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'
This gives e.g.:
>>> str_base(7,6)
'11'
Till now, it only works with bases <= 10; for the others you'd need to define an alphabet string:
import string
alphabet = string.digits + string.ascii_lowercase
and use it in the function like
res = alphabet[val % base] + res
It (probably) still doesn't work with negative numbers. If you need these, you have to add another bit of effort.
来源:https://stackoverflow.com/questions/22855842/converting-base-6-to-decimal-and-vice-versa-in-python