Advertisement
acclivity

py Binary Decimal Conversions

Feb 20th, 2022 (edited)
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. # Sample Script for Decimal to Binary, Binary to Decimal, and Binary counting
  2.  
  3. # Normally, one would use bin() and int() functions to achieve these conversions,
  4. # but it is interesting and educational to do the task without using such functions.
  5.  
  6. # by Mike Kerry - acclivity2@gmail.com
  7.  
  8. def dec2bin(dec):
  9.     out = ""
  10.     while dec:
  11.         dec, r = divmod(dec, 2)
  12.         out = str(r) + out
  13.     return out
  14.  
  15. def bin2dec(binstr):
  16.     dec = 0
  17.     for d in binstr:
  18.         dec *= 2
  19.         dec += int(d)
  20.     return dec
  21.  
  22. def get_number(prompt):
  23.     while True:
  24.         inp = input("Enter " + prompt + ": ")
  25.         try:
  26.             return int(inp)
  27.         except:
  28.             print("Invalid input. Try again")
  29.  
  30. while True:
  31.     print("\n*** MENU ***")
  32.     print("1. Decimal to Binary")
  33.     print("2. Binary to Decimal")
  34.     print("3. Binary Counting")
  35.     print("4. Quit")
  36.     answer = input("Choose an option: ")
  37.     if answer == "1":
  38.         num = get_number("decimal number")
  39.         res = dec2bin(num)
  40.         print("Decimal", num, "is", res, "in binary")
  41.     elif answer == "2":
  42.         while True:
  43.             bstr = input("\nEnter binary number: ")
  44.             for c in bstr:
  45.                 if c not in "01":
  46.                     break
  47.             else:
  48.                 break
  49.             print("Invalid binary string. Try again")
  50.         res = bin2dec(bstr)
  51.         print("Binary", bstr, "is", res, "in decimal")
  52.     elif answer == "3":
  53.         limit = get_number("decimal limit for binary counting")
  54.         for i in range(1, limit + 1):
  55.             b = dec2bin(i)
  56.             print("Decimal:", i, " = binary:", b)
  57.     elif answer == "4":
  58.         break
  59.     else:
  60.         print("Invalid choice")
  61.  
  62. print("Goodbye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement