Skip to content

Instantly share code, notes, and snippets.

@ptigas
Created May 30, 2012 11:04
Show Gist options
  • Save ptigas/2835530 to your computer and use it in GitHub Desktop.
Save ptigas/2835530 to your computer and use it in GitHub Desktop.
change base of integer
'''
convert a number (given in string format) from a base f to base t
'''
import string
def convertbase( n, f, t ) :
digits = list(string.digits+string.uppercase)
rev_digits = {}
for k,v in enumerate(digits) :
rev_digits[v] = k
# turn number to decimal
s = 0
for i, c in enumerate(n) :
s += rev_digits[n[i]]*(f**(len(n)-i-1))
# turn number from decimal to t base
res = ""
while True :
res = digits[s%t] + res
s = s // t # integer division
if s == 0 :
break
return res
# some assertations
assert convertbase('1101', 2, 3) == '111'
assert convertbase('1101', 2, 10) == '13'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment