1 """
2 Convert numbers from base 10 integers to base X strings and back again.
3
4 Original: http://www.djangosnippets.org/snippets/1431/
5
6 Sample usage:
7
8 >>> base20 = BaseConverter('0123456789abcdefghij')
9 >>> base20.from_decimal(1234)
10 '31e'
11 >>> base20.to_decimal('31e')
12 1234
13 """
14
16 decimal_digits = "0123456789"
17
20
23
26
27 - def convert(number, fromdigits, todigits):
28
29 if str(number)[0] == '-':
30 number = str(number)[1:]
31 neg = 1
32 else:
33 neg = 0
34
35
36 x = 0
37 for digit in str(number):
38 x = x * len(fromdigits) + fromdigits.index(digit)
39
40
41 if x == 0:
42 res = todigits[0]
43 else:
44 res = ""
45 while x > 0:
46 digit = x % len(todigits)
47 res = todigits[digit] + res
48 x = int(x / len(todigits))
49 if neg:
50 res = '-' + res
51 return res
52 convert = staticmethod(convert)
53
54 bin = BaseConverter('01')
55 hexconv = BaseConverter('0123456789ABCDEF')
56 base62 = BaseConverter(
57 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'
58 )
59