Package omeroweb :: Package webpublic :: Module baseconv
[hide private]
[frames] | no frames]

Source Code for Module omeroweb.webpublic.baseconv

 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   
15 -class BaseConverter(object):
16 decimal_digits = "0123456789" 17
18 - def __init__(self, digits):
19 self.digits = digits
20
21 - def from_decimal(self, i):
22 return self.convert(i, self.decimal_digits, self.digits)
23
24 - def to_decimal(self, s):
25 return int(self.convert(s, self.digits, self.decimal_digits))
26
27 - def convert(number, fromdigits, todigits):
28 # Based on http://code.activestate.com/recipes/111286/ 29 if str(number)[0] == '-': 30 number = str(number)[1:] 31 neg = 1 32 else: 33 neg = 0 34 35 # make an integer out of the number 36 x = 0 37 for digit in str(number): 38 x = x * len(fromdigits) + fromdigits.index(digit) 39 40 # create the result in base 'len(todigits)' 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