Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import sys
- time.sleep(.5)
- def typwrt(string):
- for x in string:
- sys.stdout.write(x)
- sys.stdout.flush()
- time.sleep(.01)
- typwrt('Welcome to the Decimal and Binary Translator!')
- time.sleep(1)
- print ''
- typwrt('By Kevin Shannon')
- while True:
- time.sleep(1)
- print '\n'
- typwrt('Type "db" for decimal to binary, Type "bd" for binary to decimal:')
- dbbd = raw_input()
- digits = 1
- stop = False
- bi = []
- if dbbd == "db":
- typwrt("input a decimal number:")
- number = raw_input()
- """makes sure you enter something and it is a number"""
- if len(number) > 0 and number.isdigit():
- num = int(number)
- """unless inbetween 2 2**x numbers change number until you are between them"""
- while stop == False:
- if num == 0:
- stop = True
- elif num >= 2**(digits - 1) and num < 2**digits:
- stop = True
- else:
- digits += 1
- while digits > 0:
- sub = 2**(digits - 1)
- if num - sub >= 0:
- bi.append(1)
- digits -= 1
- num -= sub
- else:
- bi.append(0)
- digits -= 1
- typwrt(str(bi).replace(',','').replace(' ', '').strip('[]'))
- else:
- typwrt("That was not a decimal number.")
- elif dbbd == "bd":
- typwrt("input a binary number:")
- number = raw_input()
- total = 0
- """makes sure you enter something and it is a number"""
- if len(number) > 0 and number.isdigit():
- digits = len(number)
- num = int(number)
- """turns string into list of each 1 and 0"""
- bi = [int(d) for d in str(num)]
- """ for each number it sees if its a 1 or 0 and adds all them up"""
- for number in bi:
- if stop == False:
- if number == 1:
- total += 2 ** (digits - 1)
- digits -= 1
- elif number == 0:
- digits -= 1
- else:
- stop = True
- else:
- stop = True
- if stop == True:
- typwrt("That was not a binary number.")
- else:
- typwrt(str(total))
- else:
- typwrt("You didn't type either db or bd!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement