Created
September 17, 2012 20:50
-
-
Save humberto-ortiz/3739682 to your computer and use it in GitHub Desktop.
Functions to read and write numbers represented in various bases
This file contains 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
# bases.py - Copyright 2010, Humberto Ortiz-Zuazaga humberto.ortiz@upr.edu | |
# Functions to read and write numbers represented in various bases | |
digits = "0123456789ABCDEF" # digits for bases 2 - 16 | |
def readnum(numstring, base): | |
"Read a string of digits in base BASE, and compute the correct decimal value" | |
value = 0 | |
for i in range(len(numstring)): | |
value = value * base | |
value = value + digits.index(numstring[i]) | |
return value | |
def repr(value, base): | |
"Return a string representation of the decimal value VALUE in the base BASE." | |
numstring = "" | |
quotient = value | |
while quotient > 0: | |
remainder = quotient % base | |
numstring = digits[remainder] + numstring | |
quotient = quotient / base | |
return numstring | |
print repr(readnum("100", 10), 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment