簡體   English   中英

你如何在Python中將十六進制轉換為三元組?

[英]How do you convert hexadecimal to ternary in Python?

我正在嘗試將任何長度的十六進制轉換為三元(雙向),特別是在Python中。 我嘗試過使用int ,但是沒用。 我也嘗試過這個名為baseconvert的庫,但只是發出錯誤, NameError: name 'base' is not defined name'base 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具有最大遞歸深度的保護(堆棧中最多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描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM