Skip to content

Instantly share code, notes, and snippets.

@ForceBru
Created March 10, 2015 17:41
Show Gist options
  • Save ForceBru/fda59da50bc68c2a527a to your computer and use it in GitHub Desktop.
Save ForceBru/fda59da50bc68c2a527a to your computer and use it in GitHub Desktop.
Python base converter
class MathExc(Exception):
def __init__(self,msg):
print "\nError: "+str(msg)+" !"
class Converter (object):
def __init__(self,base):
self._BaseN_alpha=None
self._BaseN_num=None
self._BaseN_base=None
base=int(base)
if base <=0:
raise MathExc('Base must be greater than 0')
self._BaseN_base=base
if base==2:
self._BaseN_alpha='01'
elif base==8:
self._BaseN_alpha='01234567'
elif base==16:
self._BaseN_alpha='0123456789abcdef'
elif base==62:
from string import letters, digits
self._BaseN_alpha=digits+letters
elif base==52:
from string import letters
self._BaseN_alpha=letters
else:
raise MathExc('Unsupported base')
def _FromBase62(self,String):
a=len(String)-1
num=long(0)
for let in String:
num+=(self._BaseN_alpha.find(let)+1)*(self._BaseN_base**a)
a-=1
return num
def _ToBase62(self,num):
str=''
while num:
str+=self._BaseN_alpha[(num-1)%self._BaseN_base]
num=(num-1)/self._BaseN_base
return ''.join(list(reversed(str)))
def ToBase(self,num):
try:
num=long(num)
except Exception as e:
raise MathExc(str(e))
if self._BaseN_base==62:
return self._ToBase62(num)
str=''
self._BaseN_num=int(num)
if not num:
return self._BaseN_alpha[0]
while num>0:
str+=self._BaseN_alpha[num%self._BaseN_base]
num/=self._BaseN_base
return ''.join(list(reversed(str)))
def FromBase(self,String):
try:
String=str(String)
except Exception as e:
raise MathExc(str(e))
if self._BaseN_base==62:
return self._FromBase62(String)
return int(String, base=self._BaseN_base)
a=len(String)
num=long(0)-1
for let in String:
num+=(self._BaseN_alpha.find(let)+1)*(self._BaseN_base**a)
a-=1
return num
for i in xrange(0,100):
a=Converter(16).ToBase(i)
b=long(Converter(16).FromBase(a))
assert b==i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment