-1

can someone maybe tell me what this particular lines are doing the result = result line and the one after it, i need a explanation of these two lines. Dont understand it clearly. Got it from the internet.

here is the full code

static String vigencrypt(String plain, final String key) 
{
    String result = "";
    plain = plain.toUpperCase();
    int length = plain.length();
    for (int i = 0, j = 0; i < length; i++)
    {
        char chr = plain.charAt(i);
        if (chr < 'A' || chr > 'Z') continue;
        result = result +(char)((chr + key.charAt(j) - 2 * 'A') % 26 + 'A');
        j = ++j % key.length();
    }
    return result;
}

Dont understand what these two lines do is someone can help me

  result = result +(char)((chr + key.charAt(j) - 2 * 'A') % 26 + 'A');
  j = ++j % key.length();
Martin Park
  • 11
  • 1
  • 7

1 Answers1

3

Let's go through this by line:

result = result + // Concatenate the current string in result with
(char)((chr + key.charAt(j) - 2 * (65)) % 26 + 'A'); // this guy

Let's break down that part, starting with turning A into its decimal representation of 65 (these operations will convert the chars to ints - see this answer):

(char)((chr + key.charAt(j) - 2 * (65)) % 26 + (65));

Becomes

(char)((plain.charAt(i) + key.charAt(j) - 130) % 26 + 65);

So, it's adding the value of the current plain text character to the value of the current key character. Let's say the characters are both z - this gives us

(char)((z + z - 130) % 26 + 65)

Now replace the zs with their decimal representations

(char)((122 + 122 - 130) % 26 + 65)
(char)(114 % 26 + 65)
(char)(10 + 65)
(char)(75)
'K'

What if it happens to be the other end of the letter range ( 'A' == 65 again)?

(char)((65 + 65 - 130) % 26 + 65)
(char)(0 % 26 + 65)
(char)(0 + 65)
(char)(65)
'A'

Other character combinations will encode as other characters.

(char)(('z' + 'A' - 130) % 26 + 65)
(char)((122 + 65 - 130) % 26 + 65)
(char)(57 % 26 + 65)
(char)(5 + 65)
(char)(70)
'F'

So, the first line in question is adding the next plain text character (at index i) to the next key character (at index j, which loops if there is more plaintext than key chars). It subtracts 130 (I'm not sure why - maybe to ensure it's on the standard ASCIIcode page?), then does modulo 26 and adds 65 to ensure it will output a character from A-Z, caps only. This result is appended to the previous results.

As for the second line, that's where we determine the index of the next key character. It will move up one character, while the modulo ensures that the index will loop back to the beginning rather than going beyond the key length. It might be easier to think of it as

j = (1 + j);
if (j >= key.length()) {
    j = 0;
}
Community
  • 1
  • 1
thegrinner
  • 11,546
  • 5
  • 41
  • 64