Advertisement
kevers

Binary Translator Python

Nov 13th, 2014
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. import time
  2. import sys
  3. time.sleep(.5)
  4. def typwrt(string):
  5. for x in string:
  6. sys.stdout.write(x)
  7. sys.stdout.flush()
  8. time.sleep(.01)
  9. typwrt('Welcome to the Decimal and Binary Translator!')
  10. time.sleep(1)
  11. print ''
  12. typwrt('By Kevin Shannon')
  13. while True:
  14. time.sleep(1)
  15. print '\n'
  16. typwrt('Type "db" for decimal to binary, Type "bd" for binary to decimal:')
  17. dbbd = raw_input()
  18. digits = 1
  19. stop = False
  20. bi = []
  21. if dbbd == "db":
  22. typwrt("input a decimal number:")
  23. number = raw_input()
  24. """makes sure you enter something and it is a number"""
  25. if len(number) > 0 and number.isdigit():
  26. num = int(number)
  27. """unless inbetween 2 2**x numbers change number until you are between them"""
  28. while stop == False:
  29. if num == 0:
  30. stop = True
  31. elif num >= 2**(digits - 1) and num < 2**digits:
  32. stop = True
  33. else:
  34. digits += 1
  35. while digits > 0:
  36. sub = 2**(digits - 1)
  37. if num - sub >= 0:
  38. bi.append(1)
  39. digits -= 1
  40. num -= sub
  41. else:
  42. bi.append(0)
  43. digits -= 1
  44. typwrt(str(bi).replace(',','').replace(' ', '').strip('[]'))
  45. else:
  46. typwrt("That was not a decimal number.")
  47. elif dbbd == "bd":
  48. typwrt("input a binary number:")
  49. number = raw_input()
  50. total = 0
  51. """makes sure you enter something and it is a number"""
  52. if len(number) > 0 and number.isdigit():
  53. digits = len(number)
  54. num = int(number)
  55. """turns string into list of each 1 and 0"""
  56. bi = [int(d) for d in str(num)]
  57. """ for each number it sees if its a 1 or 0 and adds all them up"""
  58. for number in bi:
  59. if stop == False:
  60. if number == 1:
  61. total += 2 ** (digits - 1)
  62. digits -= 1
  63. elif number == 0:
  64. digits -= 1
  65. else:
  66. stop = True
  67. else:
  68. stop = True
  69. if stop == True:
  70. typwrt("That was not a binary number.")
  71. else:
  72. typwrt(str(total))
  73. else:
  74. typwrt("You didn't type either db or bd!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement