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

问题描述 投票:4回答:1

我正在尝试将任何长度的十六进制转换为三元(双向),特别是在Python中。我尝试过使用int,但这没用。我也尝试过这个名为baseconvert的库,但是当我尝试使用他们提供的NameError: name 'base' is not defined命令时,它只会发出错误,base

然后,我尝试了这个脚本:

#!/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。我希望有任何长度,所以我不能只增加最大递归深度,因为它仍然不适用于每个长度。

任何帮助表示赞赏!

python hex ternary
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 description on max recursion depth

© www.soinside.com 2019 - 2024. All rights reserved.