Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sample Script for Decimal to Binary, Binary to Decimal, and Binary counting
- # Normally, one would use bin() and int() functions to achieve these conversions,
- # but it is interesting and educational to do the task without using such functions.
- # by Mike Kerry - acclivity2@gmail.com
- def dec2bin(dec):
- out = ""
- while dec:
- dec, r = divmod(dec, 2)
- out = str(r) + out
- return out
- def bin2dec(binstr):
- dec = 0
- for d in binstr:
- dec *= 2
- dec += int(d)
- return dec
- def get_number(prompt):
- while True:
- inp = input("Enter " + prompt + ": ")
- try:
- return int(inp)
- except:
- print("Invalid input. Try again")
- while True:
- print("\n*** MENU ***")
- print("1. Decimal to Binary")
- print("2. Binary to Decimal")
- print("3. Binary Counting")
- print("4. Quit")
- answer = input("Choose an option: ")
- if answer == "1":
- num = get_number("decimal number")
- res = dec2bin(num)
- print("Decimal", num, "is", res, "in binary")
- elif answer == "2":
- while True:
- bstr = input("\nEnter binary number: ")
- for c in bstr:
- if c not in "01":
- break
- else:
- break
- print("Invalid binary string. Try again")
- res = bin2dec(bstr)
- print("Binary", bstr, "is", res, "in decimal")
- elif answer == "3":
- limit = get_number("decimal limit for binary counting")
- for i in range(1, limit + 1):
- b = dec2bin(i)
- print("Decimal:", i, " = binary:", b)
- elif answer == "4":
- break
- else:
- print("Invalid choice")
- print("Goodbye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement