user3063533
user3063533

Reputation: 47

C# Ascii conversion and back

Alright, So im making a basic ceaser encryption program which offsets each character by a given amount, this is done by using the characters ASCII key then adding the amount which is should be offset by to the key.

Basically I can see why my program is not working and is not returning the string I want it to return, here is the pseudo code for encryption:

 `Type in text
  Type in encryption key
     Display Encrypt(text, key)
        function Encrypt(text,key)
          For each letter in text
            Get its ascii code
              add the key to the ascii code
                  Turn this new ascii code back to a character
                      Append character to ciphertext string

End for return ciphertext`

The first input would be a sentance, and the second input is the number for it to be offset by

Here is my C# code:

static void Main(string[] args)
    {
        Console.WriteLine("Write a Sentance!");
        string text = Console.ReadLine();
        Console.WriteLine("How many characters do you want to ofset it by?");
        int key = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(encrypt(text,key));
        Console.ReadLine();

    }

    static string encrypt(string text, int key)
    {
        string ciphertext = "";
        int y = 0;
        char[] letters = text.ToCharArray();
        for(int x = 0; x <= letters.Length; x++)
        {
            int AsciiLET = (int)letters[y];
            string Asciiletter = (AsciiLET + key).ToString();
            ciphertext += Asciiletter;
            y++;  
        }
        return ciphertext;

    }

Upvotes: 1

Views: 1307

Answers (1)

weston
weston

Reputation: 54781

A few things wrong:

  1. Can only go to one before .Length. i.e. < not <=
  2. x not y, y removed
  3. ToString on a number ((AsciiLET + key)), gives you a number in string, eg "89"
  4. Use key

Now it looks like:

static string encrypt(string text, int key)
{
    string ciphertext = "";
    char[] letters = text.ToCharArray();
    for (int x = 0; x < letters.Length; x++) // see 1
    {
        int AsciiLET = (int)letters[x]; //2
        char Asciiletter = (char)(AsciiLET + key); //3 & 4
        ciphertext += Asciiletter;
    }
    return ciphertext;
}

Upvotes: 1

Related Questions