alphabet.py 714 B

1234567891011121314151617181920212223242526272829303132
  1. # encoding=utf-8
  2. '''Shortcode arbitrary integer base alphabet conversion'''
  3. # http://stackoverflow.com/a/1119769/1524507
  4. def int_to_str(num, alphabet):
  5. '''Convert integer to string.'''
  6. if (num == 0):
  7. return alphabet[0]
  8. arr = []
  9. base = len(alphabet)
  10. while num:
  11. rem = num % base
  12. num = num // base
  13. arr.append(alphabet[rem])
  14. arr.reverse()
  15. return ''.join(arr)
  16. def str_to_int(string, alphabet):
  17. '''Convert string to integer.'''
  18. base = len(alphabet)
  19. strlen = len(string)
  20. num = 0
  21. idx = 0
  22. for char in string:
  23. power = (strlen - (idx + 1))
  24. num += alphabet.rindex(char) * (base ** power)
  25. idx += 1
  26. return num