fix incomplete base58 move from a7d3ae4
[p2pool.git] / p2pool / util / bases.py
1 def natural_to_string(n, alphabet=None):
2     if n < 0:
3         raise TypeError('n must be a natural')
4     if alphabet is None:
5         s = '%x' % (n,)
6         if len(s) % 2:
7             s = '0' + s
8         return s.decode('hex')
9     else:
10         assert len(set(alphabet)) == len(alphabet)
11         res = []
12         while n:
13             n, x = divmod(n, len(alphabet))
14             res.append(alphabet[x])
15         res.reverse()
16         return ''.join(res)
17
18 def string_to_natural(s, alphabet=None):
19     if alphabet is None:
20         assert not s.startswith('\x00')
21         return int(s.encode('hex'), 16) if s else 0
22     else:
23         assert len(set(alphabet)) == len(alphabet)
24         assert not s.startswith(alphabet[0])
25         return sum(alphabet.index(char) * len(alphabet)**i for i, char in enumerate(reversed(s)))