Search code examples
c#asciicaesar-cipher

Convert ASCII int to char


I have some code which is the beginning of a Caesar cypher using the ASCII value of a char and then adding to that value to shift it.

At the moment I have converted it back to a string to print the shifted ASCII values to TextBox3. But I need to convert 'result' back to chars in order to display the encrypted string. This is what I am struggling with.

private void button1_Click(object sender, EventArgs e)
{
    string input = textBox1.Text;
    int shift = int.Parse(textBox2.Text);

    foreach(char c in input)
    {
        int inputInt = Convert.ToInt32(c);

        int result = shift + inputInt;

        string output = Convert.ToString(result);

        textBox3.Text += output;
    }
}

Solution

  • This should work:

    private void button1_Click(object sender, EventArgs e)
    {
    
        string input = textBox1.Text;
        int shift = int.Parse(textBox2.Text);
    
        foreach(char c in input)
        {
            int inputInt = (int)c;
    
            int result = shift + inputInt;
    
            // result > 255?
    
            textBox3.Text += (char)result;
        }
    
    }