Python base 36 encoding

前端 未结 9 941
春和景丽
春和景丽 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:56

    terrible answer, but was just playing around with this an thought i'd share.

    import string, math
    
    int2base = lambda a, b: ''.join(
        [(string.digits +
          string.ascii_lowercase +
          string.ascii_uppercase)[(a // b ** i) % b]
         for i in range(int(math.log(a, b)), -1, -1)]
    )
    
    num = 1412823931503067241
    test = int2base(num, 36)
    test2 = int(test, 36)
    print test2 == num
    
    0 讨论(0)
  • 2020-11-29 03:59

    If you are feeling functional

    def b36_encode(i):
        if i < 0: return "-" + b36_encode(-i)
        if i < 36: return "0123456789abcdefghijklmnopqrstuvwxyz"[i]
        return b36_encode(i // 36) + b36_encode(i % 36)    
    

    test

    n = -919283471029384701938478
    s = "-45p3wubacgd6s0fi"
    assert int(s, base=36) == n
    assert b36_encode(n) == s
    
    0 讨论(0)
  • 2020-11-29 04:11
    from numpy import base_repr
    
    num = base_repr(num, 36)
    num = int(num, 36)
    

    Here is information about numpy.base_repr.

    0 讨论(0)
提交回复
热议问题