Click here to Skip to main content
16,020,080 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to understand the following C++ Code which I need to re-write into C#
My questions is that if I pass in the letter A I expect word to be B but instead it comes out as Z. Can someone explain the functionality.

Thanks in advance

C#
char alphabet[]   = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

void mkyScramble(char *word)
{
    unsigned int pos, last_pos, algo;
    char c[2];

    last_pos = 0;
    c[1] = '\0';

    while(*word)
    {
        strncpy(c, word, 1);
        pos = (unsigned int)strcspn(alphabet, c);

        if (pos == 26)
            word++;
        else
        {
            algo = pos + last_pos;
            if (algo > 24) algo -= 26;

            *word++ = alphabet[algo + 1];

            last_pos = pos;
        }
    }
}
Posted

C++
algo = pos + last_pos;

This is the offending line as it uses the value of last_pos to calculate the offset. Thus the string "AYA" will appear as "BZZ" because the value of last_pos when converting the second "A" will be 24 (the position of "Y") and thus it will convert "A" to "Z". Maybe your question should be: "What is the purpose of this code?"; the answer being "I have no idea".
 
Share this answer
 
Comments
Espen Harlinn 5-Apr-12 12:50pm    
Good reply :-D
Richard MacCutchan 5-Apr-12 12:59pm    
Thanks, but I had to use my debugger to figure it out.
When passing a string containing only the letter 'A', 'B' will be returned. Each output letter is build from its own offset plus the offset of the previous letter plus one with wrapping to avoid overflows.
 
Share this answer
 
I suspect this is a kind of simple Caesar cipher[^]:
"It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it in his private correspondence."
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900