What is the best way to convert raw binary data to a custom base in python?
Question: I need to convert some data to base 29 before processing and I'm using this:

    
    
    import string
    
    def datatobase(data, base):
        digs = string.digits + string.lowercase + string.uppercase
        if base > len(digs):
            return None
        digits = []
        x = int(data.encode("hex"), 16)
        while x:
            digits.append(digs[x % base])
            x /= base
        digits.reverse()
        return ''.join(digits)
    

Problem is that this small code is slowing my program too much so what would
you do to replace it?

A custom answer for base 29 only would be great too!


Answer: Base 29, only, solution for an `int` argument.

Recursive:

    
    
    s = '0123456789ABCDEFGHIJKLMNOPQRS'
    def foo(n, s=s):
        if n < 29:
            return s[n]
        a, b = divmod(n, 29)
        return foo(a) + s[b]
    

_Regular_ :

    
    
    def foo(n, s=s):    
        x = ''
        while n >= 29:
            n, b = divmod(n, 29)
            x += s[b]
        x += s[n]
        return x[::-1]
    

