<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">from math import floor

def convbase( number, base ):
    """Construct string of number converted to specified base

    USAGE:
        s = convbase( number, base )

    INPUT:
        number     - Nonnegative integer or float
        base       - integer between 1 and 36 inclusive

    OUTPUT:
        string     - string containing the number represented in the
                     indicated base.  The base is appended to the end
                     of the string.

    NOTES:
        This function accepts a decimal number and and returns the string
        representation of the number in the specified base.  This function
        only converts to bases between (inclusive) base-2 and base-36.  It
        uses the convention that hexidecimal numbers use of using alphabetic
        letters to represent values larger than 9.

    AUTHOR:
        Jonathan R. Senning &lt;jonathan.senning@gordon.edu&gt;
        Gordon College
        Written: January 21, 1999
        Revised: September 7, 2000
        Revised: January 24, 2007
        Converted to Python May 20, 2008
    """

    digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    # make sure inputs are valid

    if number &lt;= 0 or base - floor( base ) != 0 or base &lt; 2 or base &gt; 36:
        raise ValueError

    # get the integer and fractional parts of the number, and initialize
    # string that will contain the string representation of the converted
    # number

    integer_part = floor( number )
    fractional_part = number - integer_part
    s = ''

    # Convert the integer part.  This is done according to the algorithm
    # given on page 47 of "Numerical Mathematics and Computing", Fourth
    # Edition, by Cheney and Kincaid, Brooks/Cole, 1999.  Basically we
    # repeatedly divide the integer part by the new base, remembering the
    # remainders of each division.

    while integer_part &gt; 0:
	x = integer_part / base
	integer_part = floor( x )
	s = digits[ int( round( base * ( x - integer_part ) ) ) ] + s

    # if there is a fractional part then we need to append a radix point

    if fractional_part &gt; 0:
	s = s + '.'

    # Convert the fractional part.  See pages 48 and 49 Cheney and Kincaid.
    # The idea is to repeatedly multiply the fractional part by the new base,
    # remembering (and then removing) the integer part of the product.

    length_of_decimal = 0;
    while fractional_part &gt; 0 and length_of_decimal &lt; 400 / base:
	length_of_decimal = length_of_decimal + 1
	fractional_part = fractional_part * base
	x = int( floor( fractional_part ) )
	s = s + digits[x]
	fractional_part = fractional_part - x

    # Finally, append the base as a "subscript" separated from the number
    # by an underscore.

    return "%s_%d" % ( s, base )
</pre></body></html>