Home     My Faqts     Contributors     About     Help    

faqts : Computers : Programming : Languages : Python

FAQTs repaired & updated!
Thanks for your patience...
Entry Add Entry Alert - Edit this Entry

Did You Find This Entry Useful?

5 of 6 people (83%) answered Yes
Recently 5 of 6 people (83%) answered Yes

how do i convert a number in base b to a number in base 10 using python

Apr 27th, 2004 00:08

Abdel Wahab Salah, Michael Chermside, bob leron


Of course it will depend on how the number in base b is stored, but the 
most common situation is that you have a string in base b, using the 
digits from 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ. Actually, this only 
works for base 2 through base 36... for larger bases there is no 
standard convention for digits.
So the constructor for int is designed to handle any base from 2 
through 36:
    >>> int('FF', 16) # hexadecimal (base 16)
    255
    >>> int('777', 8) # base 8
    511
    >>> int('10000011', 2) # binary
    131
    >>> int('1234', 10) # decimal
    1234
    >>> int('1234') # defaults to decimal if not specified
    1234
--------------------------------------------------------------
And if you want the opposite, something like converting from decimal to 
binary you can code a function like:
def tobase(b,n,result=''):
    if n == 0:
        if result:
            return result
        else:
            return '0'
    else:
        return tobase(b,n/b,str(n%b)+result)
or, more safe and complete:
def tobase(base,number):
    global tb
    def tb(b,n,result=''):
        if n == 0: return result
        else: return tb(b,n/b,str(n%b)+result)
    if type(base) != type(1):
        raise TypeError, 'invalid base for tobase()'
    if base <= 0:
        raise ValueError, 'invalid base for tobase(): %s' % base
    if type(number) != type(1) and type(number) != type(1L):
        raise TypeError, 'tobase() of non-integer'
    if number == 0:
        return '0'
    if number > 0:
        return tb(base, number)
    if number < 0:
        return '-' + tb(base, -1*number)
bin = lambda n: tobase(2,n)
Abdel Wahab Salah
http://www.free-web-hosting.org.ru



© 1999-2004 Synop Pty Ltd