Created
May 30, 2012 11:04
-
-
Save ptigas/2835530 to your computer and use it in GitHub Desktop.
change base of integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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