0

I'm trying to figure out an efficient way (without recursion) to convert a string (number representation) from one arbitrary base to another using custom alphabet. But I cannot think of a very fast efficient method (byte shift?) to do it:

def convert_base(target, base_from, base_to):
  alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  base_to_alphabet_slice = alphabet[:base_to]
  base_from_alphabet_slice = alphabet[:base_from]
  result = ''
  for char in target:
    result += ...
  return result

Expected results:

print(convert_base('E', 16, 2))

Output: '1110'

print(convert_base('1110', 2, 16))

Output: 'E'

print(convert_base('E', 16, 10))

Output: '14'

Can someone suggest a good method for this?

  • 1
    Base conversion isn't trivial when no base is an integral multiple of the other. Why would using custom alphabet change that? – greybeard Nov 18 '20 at 23:25
  • @greybeard sorry, I'm not sure I understand the question. I need the custom alphabet so I can define a custom number system, not for the purpose of simplifying the implementation of the algorithm. For example, we use the alphabet 0123456789ABCDEF to convert numbers from base10 to base16 and back. I extended the alphabet just so I can convert larger bases. – AlekseyHoffman Nov 18 '20 at 23:35
  • Base conversion is one wrought-out topic. If interested in not-so-basic ideas, follow the link in Yuval Filmus' answer. – greybeard Nov 19 '20 at 08:36

0 Answers0