如何使用每个字母2个字母字符将字符串转换为自定义基



下面的函数使用十六进制字母'0123456789ABCDEF'将数字255 (base10)转换为'FF' (base16)

我很难弄清楚如何修改函数,使它们每个字母使用2个字母表字符,从而使数字255 (base10)使用修改后的16进制字母'x0x1x2x3x4x5x6x7x8x9xAxBxCxDxExF'转换为'xFxF' (base16)

def v2r(num, alphabet):
"""Convert base 10 number into a string of a custom base (alphabet)."""
alphabet_length = len(alphabet)
result = ''
while num > 0:
result = alphabet[num % alphabet_length] + result
num  = num // alphabet_length
return result

def r2v(data, alphabet):
"""Convert string of a custom base (alphabet) back into base 10 number."""
alphabet_length = len(alphabet)
num = 0
for char in data:
num = alphabet_length * num + alphabet[:alphabet_length].index(char)
return num
base16 = v2r(255, '0123456789ABCDEF')
base10 = r2v(base16, '0123456789ABCDEF')
print(base16, base10)
# output: FF 255
# base16 = v2r(255, 'x0x1x2x3x4x5x6x7x8x9xAxBxCxDxExF')
# base10 = r2v(base16, 'x0x1x2x3x4x5x6x7x8x9xAxBxCxDxExF')
# print(base16, base10)
# output: xFxF 255

这里有一个可能的解决方法。我认为您的错误来自于python对类型和可迭代项的定义的混淆
我修改了16进制字母表,现在它是一个项目列表。然后我也修改了一些函数来考虑这一点,看起来它很有效。

def v2r(num, alphabet):
"""Convert base 10 number into a string of a custom base (alphabet)."""
alphabet_length = len(alphabet)
result = []
while num > 0:
result = [alphabet[num % alphabet_length]] + result
num  = num // alphabet_length
return result

def r2v(data, alphabet):
"""Convert string of a custom base (alphabet) back into base 10 number."""
alphabet_length = len(alphabet)
num = 0
for char in data:
num = alphabet_length * num + alphabet.index(char)
return num
alphabet = [
'x0','x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8',
'x9', 'xA', 'xB', 'xC', 'xD', 'xE', 'xF'
]
base16 = v2r(255, alphabet)
base10 = r2v(base16, alphabet)
print(''.join(base16), base10)
#  xFxF 255

根据OP的意见:只需声明以下字母表:

hexa = '0123456789abcdef'
alphabet = [
a+b for a in hexa for b in hexa
]

我建议在开始计算之前删除"x",因此添加作为函数的第一行

alphabet=alphabet.replace('x','')

因此,您的函数将同时使用"FFF"或"xFxFxF"这两个系统。

def v2r(num, alphabet):
"""Convert base 10 number into a string of a custom base (alphabet)."""
alphabet=alphabet.replace('x','') ### added
alphabet_length = len(alphabet)
result = ''
while num > 0:
result = alphabet[num % alphabet_length] + result
num  = num // alphabet_length
return result

def r2v(data, alphabet):
"""Convert string of a custom base (alphabet) back into base 10 number."""
alphabet=alphabet.replace('x','') ### added
alphabet_length = len(alphabet)
num = 0
for char in data:
num = alphabet_length * num + alphabet[:alphabet_length].index(char)
return num

相关内容

  • 没有找到相关文章

最新更新