utils.py 947 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import string
  2. digs = string.digits + string.ascii_uppercase
  3. def base32_decode(base32_value: str) -> int:
  4. """
  5. Convert base32 string to integer
  6. Example 'A' -> 10
  7. """
  8. return int(base32_value, 32)
  9. def int2base(x: int, base: int) -> str:
  10. """
  11. Convert base 10 integer to any base string that can be represented with numbers and
  12. upper case letters
  13. Example int2base(10, 32) -> 'A'
  14. Source: https://stackoverflow.com/a/2267446/443457
  15. """
  16. if x < 0:
  17. sign = -1
  18. elif x == 0:
  19. return digs[0]
  20. else:
  21. sign = 1
  22. x *= sign
  23. digits = []
  24. while x:
  25. digits.append(digs[int(x % base)])
  26. x = int(x / base)
  27. if sign < 0:
  28. digits.append("-")
  29. digits.reverse()
  30. return "".join(digits)
  31. def base32_encode(base10_value: int) -> str:
  32. """
  33. Convert base 10 integer to base32 string
  34. Example 10 -> 'A'
  35. """
  36. return int2base(base10_value, 32)