Skip to content

Instantly share code, notes, and snippets.

@humberto-ortiz
Created September 17, 2012 20:50
Show Gist options
  • Save humberto-ortiz/3739682 to your computer and use it in GitHub Desktop.
Save humberto-ortiz/3739682 to your computer and use it in GitHub Desktop.
Functions to read and write numbers represented in various bases
# 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