uccjshrimpton

Functions Practice (Base Conversions)

Jan 7th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. from time import sleep
  2.  
  3. #converts denary to binary/octal/hex
  4. def BaseConversion(n):
  5.     binary = bin(n)[2:]
  6.     octal = oct(n)[2:]
  7.     hexadecimal = hex(n)[2:]
  8.     print("Binary:",binary)
  9.     print("Oct:",octal)
  10.     print("Hex:",hexadecimal)
  11.     return binary, octal, hexadecimal
  12.  
  13. #converts binary numbers to denary
  14. def BinToDec(n):
  15.     list_dec=[]
  16.     for i in range(0,len(n)):
  17.         list_dec.append(int(n[::-1][i])*2**i)
  18.     return(sum(list_dec))
  19.  
  20. #converts strings to ASCII
  21. def TexttoAscii(n):
  22.     binstr=""
  23.     for char in n:
  24.         pad = ""
  25.         byte=str(bin(ord(char))[2:])
  26.         while len(byte) < 8:
  27.             byte = "0" + byte
  28.         binstr += byte+" "
  29.     return binstr
  30.  
  31. #converts ASCII binary to text strings
  32. def AsciitoText(n):
  33.     count = 0
  34.     word = ""
  35.     conv = ""
  36.     for num in n:
  37.         if (num == "1") or (num == "0"):
  38.             count +=1
  39.             word += num
  40.             if count == 8:
  41.                 conv += chr(BinToDec(word))
  42.                 count = 0
  43.                 word = ""
  44.         elif num == " ":
  45.             continue    
  46.         else:
  47.             print("Error: This is not a valid binary number")
  48.     return conv
  49.  
  50. #create a text file and write to it
  51. def TextFileCreation():
  52.     return null
  53.  
  54. def Menu():
  55.     print("Built in functions demo")
  56.     print("""
  57.    1. Denary to base 2, 8, 16
  58.    2. Binary to denary
  59.    3. Text to ASCII binary
  60.    4. ASCII binary to text
  61.    5. WIP TextFileCreation
  62.    """)
  63.  
  64.     try:
  65.         choice = int(input("Type the number of the function you require:\n"))
  66.         if choice == 1:
  67.             BaseConversion(int(input("Enter a denary number to convert:\n")))
  68.             sleep(1)
  69.         elif choice == 2:
  70.             print(BinToDec(input("Enter a binary number:\n")))
  71.             sleep(1)
  72.         elif choice == 3:
  73.             print(TexttoAscii(input("Enter a text string\n")))
  74.             sleep(1)
  75.         elif choice == 4:
  76.             print(AsciitoText(input("Enter a binary string\n")))
  77.             sleep(1)
  78.         elif choice == 5:
  79.             print("Not completed yet")
  80.             sleep(1)
  81.         else:
  82.             print("Error, try again")
  83.     except ValueError:
  84.         print("Woops, you need to enter a number from the menu")
  85.     Menu()
  86. Menu()
Add Comment
Please, Sign In to add comment