Faqts : Business : Programming : Shopping For You : Python

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

17 of 24 people (71%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

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

Dec 18th, 2009 22:31
helmy mohameed, Scott Mandarich, Shopping Snooper, osama said, Joe Bloggs, johnny deep, marsh ligao, raj sandia, 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=3D''):
    if n =3D=3D 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=3D''):
        if n =3D=3D 0: return result
        else: return tb(b,n/b,str(n%b)+result)

    if type(base) !=3D type(1):
        raise TypeError, 'invalid base for tobase()'
    if base <=3D 0:
        raise ValueError, 'invalid base for tobase(): %s' % base
    if type(number) !=3D type(1) and type(number) !=3D type(1L):
        raise TypeError, 'tobase() of non-integer'
    if number =3D=3D 0:
        return '0'
    if number > 0:
        return tb(base, number)
    if number < 0:
        return '-' + tb(base, -1*number)

bin =3D lambda n: tobase(2,n)

Cheers,

Abdel Wahab Salah










http://www.cheapestwii.info/
http://marketingconsultants.abovethelaw.info/ Marketing Consultants
http://marriagecounselors.abovethelaw.info/ Marriage Counselors
http://concretemasonry.abovethelaw.info/ Concrete Masonry
http://martialarts.abovethelaw.info/ Martial Arts
http://mattresses.abovethelaw.info/ Mattresses