Advertisement
Giuseppe99999

Da decimale a binario e viceversa 1.1 Giuseppe Ferlante

Oct 31st, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #Author:Giuseppe Ferlante
  2. class binario(object):
  3.     def __init__(self,numero):
  4.         self.numero=numero
  5.     def dtb(self):#Decimale a  binario
  6.         n=self.numero
  7.         nu=""
  8.         while n!=1:
  9.             if(n%2==0):
  10.                 n=n/2
  11.                 nu="0"+nu
  12.             else:
  13.                 nu="1"+nu
  14.                 n=n/2
  15.                 n=str(n).split('.')
  16.                 n=int(n[0])
  17.         return "1"+nu
  18.     def btd(self):#Da binario a decimale
  19.         nu=0
  20.         ns=str(self.numero)
  21.         for y in range(len(ns)):
  22.             if(ns[y] == "1" or ns[y] == "0"):
  23.                 pass
  24.             else:
  25.                 raise ValueError("Errore valori accettati 1-0")
  26.                 y=len(ns)
  27.         ns=ns[::-1]#reverse
  28.         for x in range(len(ns)):
  29.             nu=nu+int(ns[x])*(2**x)
  30.         return str(nu)
  31.    
  32. def main():
  33.     global numero
  34.     print "Programmatore Giuseppe Ferlante"
  35.     while 1:
  36.         try:
  37.             try:
  38.                 scelta=input("\n\n1 Decimale-Binario\n2 Binario-Decimale\n-: ")
  39.             except SyntaxError:
  40.                 print "Errore carattere "
  41.                 continue
  42.         except NameError:
  43.             print "Non esistono scelte con le lettere "
  44.             continue;
  45.         if(scelta>2 or scelta<1):
  46.             print "Scelta non valida : %d " % (scelta)
  47.             continue;
  48.         else:
  49.             pass
  50.         try:
  51.             try:
  52.                 numero=input("Numero: ")
  53.             except SyntaxError:
  54.                 print "Errore carattere "
  55.                 continue
  56.         except NameError:
  57.             print "Errore impossibile calcolare le lettere "
  58.             continue;
  59.         if(scelta==1):
  60.             print str(numero)+": "+binario(numero=numero).dtb()
  61.         else:
  62.             try:
  63.                 print str(numero)+": "+binario(numero=numero).btd()
  64.             except ValueError:
  65.                 print "Errore il binario accetta solo 1-0"
  66.                 continue;
  67.  
  68.  
  69. if __name__=="__main__":
  70.     main()
  71. #V 1.1
  72. #Grazie ad Umberto Loria per aver fatto notare errore nello stack dei sottoprocessi ;) Grazie ;)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement