Difference between revisions of "Base Conversion"

From PeformIQ Upgrade
Jump to navigation Jump to search
(New page: =Examples= <pre> def baseconvert(n, base): """convert positive decimal integer n to equivalent in another base (2-36)""" digits = "0123456789abcdefghijklmnopqrstuvwxyz" try:...)
 
m
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Examples=
=Examples=
A couple of code examples extracted from http://code.activestate.com/recipes/65212/


<pre>
<pre>
Line 25: Line 27:


     return s
     return s
</pre>
<pre>
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and  "0" ) or ( baseN(num // b, b).lstrip("0") + numerals[num % b])
</pre>
</pre>


[[Category:Python]]
[[Category:Python]]
[[Category:Examples]]
[[Category:Mathematics]]
[[Category:Mathematics]]

Latest revision as of 17:05, 19 July 2009

Examples

A couple of code examples extracted from http://code.activestate.com/recipes/65212/

def baseconvert(n, base):
    """convert positive decimal integer n to equivalent in another base (2-36)"""

    digits = "0123456789abcdefghijklmnopqrstuvwxyz"

    try:
        n = int(n)
        base = int(base)
    except:
        return ""

    if n < 0 or base < 2 or base > 36:
        return ""

    s = ""
    while 1:
        r = n % base
        s = digits[r] + s
        n = n / base
        if n == 0:
            break

    return s
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and  "0" ) or ( baseN(num // b, b).lstrip("0") + numerals[num % b])