如何在Python中将十六进制转换为三进制?

4
我正在尝试将任意长度的十六进制转换为三进制(双向),特别是在Python中。我尝试使用int,但没有成功。我还尝试了一个名为baseconvert的库,但当我尝试使用他们提供的base命令时,它会报错:NameError: name 'base' is not defined
然后,我尝试了这个脚本:
#!/usb/bin/python

def toStr(n,base):
   convertString = "0123456789ABCDEF"
   if n < base:
      return convertString[n]
   else:
      return toStr(n//base,base) + convertString[n%base]

#####################

hex = "6a48f82d8e828ce82b82abc12397812389721389712387912321387913248723081270243872308472384723472304723089547230485728347283470928347087230457340587304857034570345708345034509348509834509834598230948230948203948092348092348092348092385409283092340923409823490823409820394820934809234809abababababab2345098234092349084238903244444444444444444444444444444442430898888888888888888888999999999999999999999997"
# hex = "6A48F82D8E828CE82B82"
# hex = "e30ac3baf3ab3ffedb8a02dfcc962e2c455650c1614d63ba9a058685da6f04f1c282a5214e65a47506d65a7b9a80d85fc7365aabce539a0696ff2157485d720a7368613531323a20646333656537636164333839396538333839316236376137376136356531356362346665383262356465646363623631373237383833633761306232663064366630396461643264316461393937336432663134333338393161653264373534623864316363653835656433656635353865363634626665656135373531363820696e6465782e68746d6c"

print("hex  =", hex)

# dec = int(hex, 16)
# print("dec  =", dec)

tern = (toStr(int(hex, 16),3))
print("tern =", tern)

rehex = (toStr(int(tern, 3),16))
print("rehex  =", rehex)

#####################


# unhex: Convert Hexadecits to Trits
# tern = ""
# for i in hex:
#     digit = (toStr(int(i, 16),3))
#     tern += digit
#     # print("tern =", tern)

#     # print(i)
# print("tern =", tern)

这段代码似乎是双向的,但是会出现一个错误:RecursionError: maximum recursion depth exceeded in comparison。我希望这段代码可以适用于 任何长度,所以我不能只增加最大递归深度,因为这样并不能解决所有长度的问题。

非常感谢您的帮助!


你看过https://dev59.com/slsW5IYBdhLWcg3w0Z4j吗? - Liora Haydont
2
如果你不想超过限制,我认为递归并不是一个理想的路径,你应该尝试使用循环。 - Liora Haydont
1
不相关的,但你的NameError: name 'base' is not defined错误可以通过以下方法解决:要么import baseconvert,然后使用baseconvert.base("4080.5", 10, 16, string=True);要么使用from baseconvert import *,然后直接调用base("4080.5", 10, 16, string=True)。显然文档编写者认为每个人都会使用最后一种语法。 - Jongware
1个回答

3

您的代码按预期工作,执行了您想要的操作。问题在于Python默认有一个最大递归深度保护(堆栈最多1000层)。您可以增加它,但这不是非常可扩展的。您真正想做的是以迭代方式重写您的代码。

您的代码可能看起来像这样:

def toStr(n, base):
    convertString = "0123456789ABCDEF"
    result = ''
    while n > base:
        result = result + convertString[n%base]
        n = n//base
    if n > 0:
        result = result + convertString[n]
    return result

更多信息: 关于最大递归深度的SO说明


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接