#! /usr/bin/env python # -*- coding: UTF-8 -*- """ PyConverter, convertitore in python creato da Frafra (francesco.it@gmail.com) col contributo di C8E e Drew Perttula This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. """ __module_name__ = "PyConverter" __module_version__ = "2.2" __module_description__ = "Converirore di numeri in varie basi" choice = { "0":"quit", "1":"binario", "2":"decimale", "3":"ottale", "4":"esadecimale" } valids = { "binario":"01", "decimale":"0123456789", "ottale":"01234567", "esadecimale":"0123456789ABCDEF" } def conv(number, fromdigits, todigits): x = 0L for digit in str(number): x = x * len(fromdigits) + fromdigits.index(digit) res = "" while x > 0: digit = x % len(todigits) res = todigits[digit] + res x /= len(todigits) return res def ask(message, valid_chars, min_len = 1, max_len = 10, max_retry = 10): for each in xrange(max_retry): answer = raw_input(message + " ") for char in answer: if char.upper() not in valid_chars: print "- Formato non valido, riprova." break else: if min_len <= len(answer) <= max_len: return answer else: print "- Formato non valido, riprova." print "- L'utente e' troppo stupido per usare questo programma." def quit(): print "- Arrivederci." raise SystemExit(0) while 1: menu = "(0) Esci, (1) da binario, (2), da decimale, (3) da ottale, " menu += " (4) da esadecimale:" da = choice[ask(menu, "01234", 1, 1)] if da == "quit": quit() menu = "(0) Esci, (1) a binario, (2), a decimale, (3) a ottale, " menu += " (4) a esadecimale:" a = choice[ask(menu, "01234", 1, 1)] if a == "quit": quit() num = str(ask("- Inserire un numero %s:" % da, valids[da])).upper() print "- L'equivalente numero", a, "รจ", conv(num, valids[da], valids[a])