* Christopher Howard <christopher.howard@frigidcode.com> [110802 21:15]:
> other bases. The function shall take two parameters: a parameter "d"
> representing the original decimal number, and a parameter "n"
> representing the base to which to convert. The function shall return a
> string representation of the converted number.
This is what I have: (written some time ago)
def enbase(num,base,uc=0):
"""Change a to `base' number. Up to base-36 is supported without
special notation. Optional arg `uc' forces alphas to upper case."""
num_rep={ 10:'a', 11:'b', 12:'c', 13:'d', 14:'e', 15:'f', 16:'g', 17:'h', 18:'i', 19:'j',
20:'k', 21:'l', 22:'m', 23:'n', 24:'o', 25:'p', 26:'q', 27:'r', 28:'s', 29:'t',
30:'u', 31:'v', 32:'w', 33:'x', 34:'y', 35:'z'}
res = []
current = num
while current != 0:
remainder = current % base
if 36 > remainder > 9:
remainder_string = num_rep[remainder]
elif remainder >= 36:
remainder_string='('+str(remainder)+')'
else :
remainder_string = str(remainder)
res.append(remainder_string)
current = current / base
if uc :
return ''.join(res).upper()
else :
return ''.join(res)
## test
## base > 36
>>> tlib.enbase(118,40)
'(38)2'
>>> tlib.enbase(47,40)
'71'
## base < 36
>>> tlib.enbase(47,16)
'f2'
>>> tlib.enbase(47,16,1)
'F2'
>>> tlib.enbase(100,2)
'0010011'
>>> tlib.enbase(126,2)
'0111111'
>>> tlib.enbase(128,2)
'00000001'
>>> tlib.enbase(128,16)
'08'
>>> tlib.enbase(128,8)
'002'
>>> tlib.enbase(127,16)
'f7'
>>> tlib.enbase(127,16,1)
'F7'
-- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com --------- To unsubscribe, send email to <aklug-request@aklug.org> with 'unsubscribe' in the message body.Received on Fri Aug 5 10:08:16 2011
This archive was generated by hypermail 2.1.8 : Fri Aug 05 2011 - 10:08:16 AKDT