Aleah Strength Aleah Strength - 1 year ago 53
C# Question

How can I stop my counter from going to 48 from 0 after it records x for look up in a character array?

Below I have included a snippet of my decrypt method using a polybius square. I am wanting to take the first two user inputs and turn them into coordinates to look up what letter in the square matches the input numbers. My code works for the x value and then assigns the y as 48. i need help finding to incriment between x and y without changing y to 48.

public string DecryptMessage(string userInput)
string outputMessage = string.Empty;

char[,] alphaValues = new char[5, 5] {
{'A', 'B', 'C', 'D', 'E'},
{'F', 'G', 'H', 'I', 'K'},
{'L', 'M', 'N', 'O', 'P'},
{'Q', 'R', 'S', 'T', 'U'},
{'V', 'W', 'X', 'Y', 'Z'},

char[] userInputArray = userInput.ToCharArray();

for (int i = 0; i < userInputArray.Length; i++)
int x = Convert.ToInt32(userInputArray[i]); i++;
//after this point i somehow changes from 0 to 48 with the incriment
//if i get this fixed the decrypt will work, still trying to figure this out

int y = Convert.ToInt32(userInputArray[i]);

char letterToReturn = alphaValues[x, y];

string outputLetter = letterToReturn.ToString();
outputMessage += outputLetter;

return outputMessage;

Answer Source

The problem is that you're converting the character representation of the digit to a integer, which is going to be the numeric value that represents that character rather than the digit you're looking for.

Try this:

int x = userInputArray[i++] - '0';
int y = userInputArray[i] - '0';
char letterToReturn = alphaValues[x, y];

Since '0' through '9' are represented by 48 through 57, subtracting '0' from the character effectively turns the digit character into the actual number.

'0' is 48, '1' is 49, and so on all the way up to '9' being 57, so '1' - '0' is 49 - 48 or just 1. '9' - '0' is 57 - 48 or just 9.

Of course this little trick depends on the character set being used, but it works for ASCII and unicode.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download