alex jarvis
alex jarvis

Reputation: 27

Program that converts numbers to letters both ways

I'm working on a program that encodes and decodes letters to numbers. I have the Encoding properly built but the decoding is giving me problems. I'm using int to char conversions with the ASCII table as the key. It doesn't seem like the conversion logic for the decoding is right but I really have no idea how to fix it. This is my first time using this conversion method so I still don't fully understand it.

*edit This is on a windows form app that has three buttons and two text boxes. Encode is one button, and you type in a sentence and it outputs in in numbers for each letter. Decode is another but it does the opposite type in numbers and get words. the third button is clear so thats not important. Sorry I left this out of the initial question.

class LetterCodeLogic
{
    public static string Encode(string msg)
    {
        string result = "";
        string m = msg.ToUpper();
        char c;
        int x;
        for(int i = 0; i < m.Length; i++)
        {
            c = Convert.ToChar(m[i]);
            x = c;
            if (x == 32)
            {
                x = 0;
            }
            else
            {
                x -= 64;
                if (x < 1 || x > 26)
                {
                    x = 99;
                }
            }
            result += x.ToString() + " ";
        }

        return result;
    }
    public static string Decode(string msg)
    {
        string result = "";
        string[] nums = msg.Split(',');
        char c;
        int x;
        for (int i = 0; i < msg.Length; i++)
        {
            x = Convert.ToChar(msg[i]);
            c = (char)x;
            if (c == 0)
            {
                c = (char)32;
            }
            else
            {
                c -= (char)64;
                if (c < 65 || c > 90)
                {
                    c = (char)35;
                }
            }
            result += c.ToString() + " ";
        }

        return result;
    }
    
}

Upvotes: 1

Views: 450

Answers (1)

John Wu
John Wu

Reputation: 52280

I find problems like this are far easier when you break them into parts. First, write functions that convert a single character to a number or vice versa.

static public byte Encode(char c)
{
    if (c == ' ') return 0;
    if (c >= 'A' && c <= 'Z') return (byte)(c - 'A' + 1);
    return 99;
}

static public char Decode(byte n)
{
    if (n == 0) return ' ';
    if (n >= 1 && n <= 27) return (char)(n + 'A' - 1);
    return '#';
}

Now the functions you need are very easy to write:

static public string Encode(string stringInput)
{
    return string.Join(" ", stringInput.Select(Encode).Select( b => b.ToString() ));
}

static public string Decode(string numericInput)
{
    return new string(numericInput.Split(' ').Select( n => byte.Parse(n)).Select(Decode).ToArray());
}

Upvotes: 4

Related Questions