Advertisement
egbie

Binary to text and text to binary converter

Apr 29th, 2014
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.86 KB | None | 0 0
  1. ###############################################################################
  2. # Binary To Text and a Text to Binary converter
  3. # Started on sun 27  13:12:18 hrs
  4. # Finished on Tuesday 14:56:18 hrs
  5. # Updated on Wed 30 April 2014 15:00 hrs
  6. # Language python 2.7
  7. # created by Egbie Anderson
  8.  
  9. # A simple program in which text is entered by the user. Depending on the users choice
  10. # within the menu the text is either converted to binary or into to text
  11. #
  12. # This program works by reading and writing files from and to a hard drive
  13. # The program was written in python in 2.7x and therefore will not work in python 3.x series
  14. #
  15. # Licence < free>
  16. # Operating System <any>
  17. # All rights 2014
  18. # Copy right <None>
  19. ###############################################################################
  20.  
  21. # built in python modules
  22. import os
  23. import sys
  24. import webbrowser
  25. from time import sleep
  26. from platform import system
  27.  
  28. ########################################################################
  29. # Operating System class
  30. ########################################################################
  31. class OperatingSystem(object):
  32.     '''Responsible for all things that has to with the operating system'''
  33.    
  34.     def get_operating_system(self):
  35.         '''returns the user operating system'''
  36.         return system()
  37.  
  38.     def get_current_path(self):
  39.         '''return the current file path'''
  40.         return os.getcwd()
  41.  
  42.     def join_path(self, file_name):
  43.         '''takes a file name and concatenate it with the current directory path'''
  44.         return (os.path.join(self.get_current_path(), file_name))
  45.  
  46.     def command(self, command, file_path):
  47.         '''performs a specific command on the operating system'''
  48.         os.system('%s %s' %(command, file_path))
  49.  
  50. ########################################################################
  51. # InputOutput class
  52. ########################################################################
  53. class InputOutput(object):
  54.     """The class is responsible for anything that involves retreiving or storing information
  55.   to a hard drive
  56.   """
  57.     def load(self, file_path):
  58.         '''load(str) -> return(str)
  59.  
  60.       Takes a file or a file path and loads it into memory
  61.       '''
  62.         try:
  63.             self.file = open(file_path, "r")
  64.         except IOError:
  65.             print "[!] File not found, closing program"
  66.             exit(0)
  67.         else:
  68.             self.out_file = self.file.readlines()
  69.             self.file.close()
  70.             return self.out_file
  71.            
  72.     def create_text_file(self, filename, info_to_be_written, mode = 'w'):
  73.         """creates a text file or a clipboard and then writes information to that file"""
  74.  
  75.         self.files = open(filename, mode)
  76.         self.files.write(info_to_be_written)
  77.         self.files.write("\n")
  78.         self.files.close()
  79.  
  80. ########################################################################
  81. # Converter class
  82. ########################################################################
  83. class Converter(object):
  84.     '''responsible for converting data from one thing to another'''
  85.  
  86.     # private function
  87.     def _add_padding(self, bin_str, padding=8):
  88.         '''add_padding(int) -> return(int)
  89.  
  90.       Takes a binary string and checks if the length of that
  91.       the string is 8. If True the binary string is returned and
  92.       if False the binary string is padded with 0 until the length
  93.       is 8. This ensures the method is working with bytes.
  94.  
  95.       >>> _add_padding(10)
  96.       00000010
  97.  
  98.       >>> _add_padding(11110000)
  99.       11110000
  100.       '''
  101.         # return the str if str is of length eight
  102.         if len(bin_str) == padding:
  103.             return bin_str
  104.  
  105.         # add padding if the string does not meet the right specification
  106.         while len(bin_str) < padding:
  107.             bin_str = "0" + bin_str
  108.          
  109.         return bin_str
  110.  
  111.     def convert_to_binary(self, message):
  112.         '''convert_to_binary(void) -> return(str)
  113.  
  114.       Takes a string and returns it binary representation
  115.  
  116.       >>> convert_to_binary("Shannon Morse)
  117.       '01010011011010000110000101101110011011100110111
  118.       101101110001000000100110101101111011100100111001101100101'
  119.  
  120.       >>> convert_to_binary(PadreJ)
  121.       '010100000110000101100100011100100110010101001010'
  122.       '''
  123.  
  124.         self.binary_str = ""
  125.         self.binary_string = ""
  126.  
  127.         # changes the letters in the string into its ascii value representation
  128.         for char in message:
  129.             self.number = ord(str(char))
  130.  
  131.             # turns an integer into a binary string
  132.             while self.number > 0:
  133.                
  134.                 self.binary_string = str(self.number % 2) + self.binary_string
  135.                 self.number = self.number//2
  136.  
  137.             self.binary_str += self._add_padding(self.binary_string) # checks the padding and stores it in a new string
  138.             self.binary_string = ""                #  reset the binary string to an empty string and begin anew
  139.  
  140.         return self.binary_str
  141.  
  142.     def convert_binary_to_integer(self, binary):
  143.         '''convert_binary_to_integer(str) -> return(str)
  144.       Takes a binary string and converts it into an integer
  145.       returns: an Integer
  146.  
  147.       >>> convert_binary_to_integer('01100001')
  148.       97
  149.       >>> convert_binary_to_integer('01100001')
  150.       119
  151.      
  152.       '''
  153.         self.decimal = []
  154.         self.binary_position = 0
  155.  
  156.         # starts from the right of the binary string. If the binary string at that position is a
  157.         # 1. Then the index in which the 1 occurs is raised to the power of 2
  158.         for pos in xrange(len(binary) -1, 0, -1):
  159.            
  160.              if binary[pos] == '1':
  161.                  self.decimal.append(2 ** self.binary_position)      # raise the index by the power of 2
  162.              self.binary_position += 1
  163.                
  164.         return (sum(self.decimal))
  165.            
  166.     def convert_binary_to_string(self, binary_str):
  167.         '''convert_binary_to_string(str) -> return(str)
  168.  
  169.       Takes a binary string and returns a sentence that all the character
  170.       and letters that can be found on the ascii table
  171.  
  172.       str1 = '010000110110111101100100011010010110111001100111001100010011000000110001'
  173.       str2 = '01010011011010000110000101101110011011100110111101101110'
  174.       str3 = '01000100011000010110110001100101'
  175.       str4 =  '010100000110000101100100011100100110010101001010'
  176.      
  177.       >>> convert_binary_to_string(str1)
  178.       'Coding101'
  179.      
  180.       >>> convert_binary_to_string(str2)
  181.       Shannon
  182.      
  183.       >>> convert_binary_to_string(str3)
  184.       Dale
  185.      
  186.       >>> convert_binary_to_string(str4)
  187.       'PadreJ'
  188.      
  189.       '''
  190.         self.start = 0
  191.         self.end  = 8
  192.         self.text = ""
  193.  
  194.         # Takes a binary string and splits it into bytes. Each byte is then converted to
  195.         # its integer counter part. Next the integer is then converted into a character
  196.         # that can be found within an ascii table.
  197.         for block in range(len(binary_str)/8) :
  198.  
  199.             self.byte = binary_str[self.start: self.end]                          # the first byte of the number
  200.             self.start, self.end = self.end, self.end + 8
  201.        
  202.             # a method call to convert the byte into an integer
  203.             self.integer = self.convert_binary_to_integer(self.byte)
  204.  
  205.             # use the ascii table to convert the integer to its ascii couterpart
  206.             self.text += chr(self.integer)
  207.  
  208.         return self.text
  209.    
  210. ########################################################################
  211. # Friendly user inteface class
  212. ########################################################################            
  213. class Interface(OperatingSystem):
  214.     '''The class is the inteface class. It hides all the complexes of the classes and
  215.   provides the user with an easy way of converting binary to text or text to binary via a
  216.   friendly text menu. It also inherits from the OperatingSystem class'''
  217.    
  218.     def inform_user(self):
  219.         '''inform the user of what about to happen'''
  220.  
  221.         print "[*] Please wait preparing writing pad for user.."
  222.         sleep(0.05)
  223.         print "[*] Please wait open writing pad for user in new window... "
  224.         sleep(0.05)
  225.        
  226.     def check_and_open(self, file_path):
  227.         '''check_and_open(str) -> return(None)
  228.  
  229.       Depending on what operating system the user is using
  230.       a specific command is used to open the default editor
  231.       on the user computer
  232.       '''
  233.        
  234.         if self.get_operating_system() == "Linux":
  235.                    
  236.             self.command('xdg-open', self.join_path(file_path))
  237.             raw_input("[*] Press Enter to continue ")
  238.      
  239.         elif self.get_operating_system() == "Windows":
  240.            
  241.             self.command('notepad', self.join_path(file_path))
  242.             raw_input("[*] Press Enter to continue ")
  243.  
  244.         else:
  245.             self.output = webbrowser.open(self.join_path(file_path))
  246.             raw_input("[*] Press Enter to continue ")
  247.            
  248.     def menu(self):
  249.         '''menu(void) -> return(int)'''
  250.        
  251.         print '''
  252.  
  253.       [+] A simple program in which text is entered by the user. It is then
  254.       [+] converted to binary or from binary to text if your option was 2
  255.      
  256.       =======================================
  257.  
  258.           [1] Convert Text to Binary
  259.           [2] Convert  Binary to Text
  260.           [3] Exit
  261.  
  262.       =======================================
  263.       '''
  264.  
  265.         self.choice = int(raw_input("[*] Enter your choice : "))
  266.            
  267.         if self.choice == 1:
  268.             self.inform_user()
  269.             self.check_and_open("text_file.txt")
  270.             return 1
  271.  
  272.         elif self.choice == 2:
  273.  
  274.             self.inform_user()
  275.             print "[*] Enter the binary you would like to convert to text "
  276.             self.check_and_open("binary_file.txt")
  277.             return 2
  278.  
  279.         elif self.choice == 3:
  280.             print "[*] Exiting menu and closing program"
  281.             sleep(0.2)
  282.             print "[*] Goodbye, see you soon!!"
  283.             #sys.exit(0)
  284.         else:
  285.             print "[!] your choice must be either 1,2,3, exiting program!!!"
  286.            
  287.                
  288. # the main program
  289. def main():
  290.      
  291.       choice =  user_interface.menu()  # return the user choice from the text menu
  292.      
  293.       if choice == 1:
  294.           txt_file = data.load("text_file.txt")[9:]
  295.  
  296.          # convert to binary and display to user
  297.           for f in txt_file:
  298.               binary = convert.convert_to_binary(f)
  299.               data.create_text_file("binary_file.txt",  binary, "a")
  300.  
  301.           print "\n[*] Conversion successful."
  302.           sleep(0.3)
  303.           print "[*] A copy of file binary_file.txt is in your current working directory..."
  304.           sleep(0.3)
  305.           print "[*[ Displaying binary file in new window please wait..."
  306.           sleep(0.3)
  307.           user_interface.check_and_open("binary_file.txt")
  308.  
  309.       elif choice == 2:
  310.  
  311.          binary_txt_file = data.load("binary_file.txt")[4:]
  312.  
  313.          # Turns the binary string list into a string removes any spaces and any newlines and converts it back
  314.          # to a string. This ensures that even if the user enters the binary with spaces such as 01010 0001 000
  315.          # the outcome will still be the same
  316.          binary_txt_file = [''.join((''.join(''.join(binary_txt_file).split(' '))).split('\n'))]
  317.        
  318.          # convert to text and display to user
  319.          for f in binary_txt_file:
  320.      
  321.              string = convert.convert_binary_to_string(f)
  322.              data.create_text_file("binary_to_string.txt",  string.strip("\n"), "a")
  323.  
  324.          print "\n[*] Succesful converted binary to text."
  325.          sleep(0.3)
  326.          print "[*] A copy of file binary_to_string.txt is in your current working directory..."
  327.          sleep(0.3)
  328.          print "[*] Preparing binary_to_string.txt  file to display to user..."
  329.          sleep(0.3)
  330.          print "[*] Opening file to user in new window..."
  331.          user_interface.check_and_open("binary_to_string.txt")
  332.        
  333. # if the program is run and not imported the following things are initialised and created
  334. if  __name__ == "__main__":
  335.  
  336.     user_interface = Interface()
  337.     data = InputOutput()
  338.     convert = Converter()
  339.    
  340.     # create text file
  341.     data.create_text_file("text_file.txt", ("#"*80))
  342.     data.create_text_file("text_file.txt", ("[*] Hello user enter the text you want to turn to binary"), "a")
  343.     data.create_text_file("text_file.txt", ("[*] Just below the second hash line"), "a")
  344.     data.create_text_file("text_file.txt", ("[*] Or copy and paste any text into the editor"), "a")
  345.     data.create_text_file("text_file.txt", ("[*] When entering your text whether pasting or entering by hand make sure there"), "a")
  346.     data.create_text_file("text_file.txt", ("[*] is at least one new line between your text and the last hash line."), "a")
  347.     data.create_text_file("text_file.txt", ("[*] or your text will not show up in the converted binary file."), "a")
  348.     data.create_text_file("text_file.txt", ("[*] Save the file and close"), "a")
  349.     data.create_text_file("text_file.txt", ("#"*80),"a")
  350.     data.create_text_file("text_file.txt", "\n", "a")
  351.    
  352.     # create binary file
  353.     data.create_text_file("binary_file.txt", ("#"*80))
  354.     data.create_text_file("binary_file.txt", "[*] Your text in binary form\n", "a")
  355.     data.create_text_file("binary_file.txt", ("#"*80), "a")
  356.     data.create_text_file("binary_file.txt", "\n", "a")
  357.  
  358.     # create binary_to_string file
  359.     data.create_text_file("binary_to_string.txt", ("#"*80))
  360.     data.create_text_file("binary_to_string.txt", "[*] converted binary to text format\n", "a")
  361.     data.create_text_file("binary_to_string.txt", ("#"*80), "a")
  362.     data.create_text_file("binary_to_string.txt", "\n", "a")
  363.  
  364.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement