Convertir du binaire au décimal

afafarfa Messages postés 1 Date d'inscription   Statut Membre Dernière intervention   -  
papanou1965 Messages postés 37 Date d'inscription   Statut Membre Dernière intervention   -
bonjour tout le monde, je suis débutante en programmation je cherche à écrire une fonction pour convertir un nombre du binaire au décimal mais je bloque voilà ce que j'ai fais:
def decimal(A):
         def puissance(x,k):
                if k==0:
                    return 1
                if k==1:
                    return x
                else:
                    return x*puissance(x,k-1)
          b=0
          c=0
          for i in range (0,len(A)):   
                if A[i]==0:
                    b=0
                else :
                    b=puissance(2,len(A)-1-i)
                    c+=b
          return c
print(decimal("1001011"))




au début j'ai écris une fonction pour calculer les puissances je pense que j'en aurai besoin pour calculer les puissances de 2, le reste c'est pour la conversion

le programme doit normalement afficher le nombre 75, mais il affiche 127, je ne sais pas où est le problème.

merci d'avance
A voir également:

2 réponses

jisisv Messages postés 3645 Date d'inscription   Statut Modérateur Dernière intervention   934
 
A moins que ce ne soit un exercice (encore un exercice qui n'apprend pas à utiliser les outils préexistants et facilités d'un langage), ce code est inutile et imbuvable (pour calculer une puissance on utilise Horner, notamment )
Ceci suffit:
string37='100101'
print(int(string37, 2))


Utilise ton interpréteur préféré::
>>> doc=int.__doc__
>>> print( doc )
int(x=0) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)

Gates gave ^H sold you the windows.
GNU gave us the whole house.(Alexandrin)
2