Python base 36 encoding

前端 未结 9 1002
春和景丽
春和景丽 2020-11-29 03:21

How can I encode an integer with base 36 in Python and then decode it again?

9条回答
  •  甜味超标
    2020-11-29 03:47

    This works if you only care about positive integers.

    def int_to_base36(num):
        """Converts a positive integer into a base36 string."""
        assert num >= 0
        digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    
        res = ''
        while not res or num > 0:
            num, i = divmod(num, 36)
            res = digits[i] + res
        return res
    

    To convert back to int, just use int(num, 36). For a conversion of arbitrary bases see https://gist.github.com/mbarkhau/1b918cb3b4a2bdaf841c

提交回复
热议问题