bindecode.py, in English This Python program converts text into space-delimited binary text strings and vice versa. For example, a file containing "foo" will generate a file containing "01100110 01101111 01101111" and a file containing "01100010 01100001 01110010" will generate a file containing "bar". Since command tail processing is supported, we need to include the two import statements. If you invoke w/ no tail or w/ -h or --help you'll get a usage message. The very last line of code has the effect of launching the main function and passes to it the command tail. This in turn will issue a usage message or will launch the doit function, passing it the command tail. doit opens both input and output files and then, depending on whether you are decoding or encoding, processes accordingly. decoding: The single-element list line gets loaded w/ the binary text. Any trailing space is removed. The multi-element list parts is next populated w/ each binary chunk using the space character as the split delimiter. You then cycle thru each chunk and call binToChar on it. binToChar generates the decimal number that corresponds to the binary chunk and then returns the letter that corresponds to it. The builtin functions pow and chr are used. For example, 01100110 will result in 102 which in turn will become the letter f. These letters get written to the output file. When done, the file is closed. encoding: The multi-element list lines gets loaded w/ each line from the input file. Each of these lines is then processed, character by character, by calling charToBin on it. charToBin first turns the letter into its decimal counterpart (the ord function) and then a string is built by concatenating a 1 or a 0 on the left when the decimal number contains the corresponding power of 2. The binary string is padded on the left w/ 0's to make its length 8. The string is space-padded on the right and passed back to be written to the output file. When done, the file is closed. Note: general remarks about Python: 1. indentation is important 2. functions are defined so that functions they reference appear above them (I'm not sure this is necessary but it makes the program easier to understand) 3. lists are important 4. Python programs can be run at a command prompt via (for example): C:\1-10-14>python bindecode.py e wolf.txt wolf.enc C:\1-10-14>python bindecode.py d wolf.enc wolf.txt
You can count on Python being installed on Linux systems. Under Windows, I use the "Hello World" installation which gives you idle (a GUI / Integrated Development Environment) etc. etc.
|