Pages

Saturday, December 14, 2013

Python: Working with ASCII

Converting text to ASCII and ASCII to text can be done with ease by python.

Conversion from Text (single character) to ASCII can be done by ord() function and the reverse by chr() function

Example:
>>> ord("A")
65
>>> chr(65)
'A'
>>> ord(":")
58
>>> chr(77)
'M'


While I was trying out some basic challenges at Hackthissite.org, there was a challenge there to that gave an encrypted string. The string was encrypted using a modification of shift cipher where every character was shifted one time more than the previous character, shift starting from 0. So taking advantage of the above mentioned functions, I wrote a program that does the decryption and encryption in that method
def encrypt():
    ciphertext = raw_input("Enter the plaintext :")
    plaintext = ""
    count = 0 
    for item in ciphertext:
        item = chr(ord(item)+count)
        count += 1
        plaintext += item
    print plaintext

                        
def decrypt():
    ciphertext = raw_input("Enter the ciphertext :")
    plaintext = ""
    count = 0 
    for item in ciphertext:
        item = chr(ord(item)-count)
        count += 1
        plaintext += item
    print plaintext
                        




No comments:

Post a Comment