Could someone possibly walk through what exactly this chunk of code is doing? It's from a program to encrypt a string using the vigenere cipher the user inputs along with a key.
I've never worked with a vigenere cypher, but this seems pretty straightforward. The loop seems to iterate over each character of upperText, and also iterates over each character of the key to encrypt it with the cypher. For clarity, I'm assuming that the system is using ASCII for numerical representation of characters, although this seems to be written in a way to not depend on that specifically.
- line 1: - iterates over each character of upperText
Your counter 'i' is used to point to the index of the character being evaluated in upperText, and is incremented by one for each iteration.
- line 3: - isolates the current character of upperText being evaluated into the variable 'c'
- line 5: - Checks to see if the current character is outside of the range [A-Z]
If so, it skips any further evaluation of the character by skipping the rest of the loop body, and goes to the next character/iteration of the loop (back to line 1, to increment the counter 'i', and evaluate the conditional statement)
- line 6:
Let's break it down:
Code:
[b](c + key.charAt(j) - 2 * 'A')[/b]
This looks like it adds the numerical value of the evaluated character 'c' to the numerical value of the current 'j' index of the 'key' string, and then subtracts the product of 2 and the numerical value of 'A' (e.g. in ASCII, 'A' == 65).
This would effectively encrypt the character, but to make sure that the resulting value falls within range of the characters needed (i.e. [A-Z])...
Code:
((c + key.charAt(j) - 2 * 'A')[b] % 26 + 'A'[/b])
...the value is modded by 26 (the length of the range), which will always give you a number between 0 and 25.
The numerical value of 'A' is then added to your modded value to make sure that it falls within the appropriate range of characters (e.g. in ASCII, [A-Z] == [65-90]).
The resultant value, at this point, is still an integer, so to get the character value of this,
Code:
[b](char)[/b]((c + key.charAt(j) - 2 * 'A') % 26 + 'A')
the resultant value is casted into a
char type.
Code:
[b]result += [/b](char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
This
char value is then concatenated to the end of the 'result' string.
- line 8:
Here is where it increments the counter 'j', which is used to iterate over each character in the 'key' string. Note that it not only increments the counter by one, but it also mods this value against the length of the 'key' string.
What this does, is makes sure that if the index 'j' goes beyond the length of the key, it will loop the index 'j' back to the beginning of the 'key' string.
The result of this should be your encrypted string in the variable 'result'.
I'm sure if I missed something, or completely misinterpreted some logic, one of the other fine people here will jump on to help clarify.