1

HZROT.cpp:

#include "HZROT.h"

std::string ROTEncode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (a >= 'A' && a <= 'Z')
            result += ((int)a + rot) % (int)'Z';
        else if (a >= 'a' && a <= 'z')
            result += ((int)a + rot) % (int)'z';
        else
            result += a;
    }
    return result;
}
std::string ROTDecode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (a >= 'A' && a <= 'Z')
                result += ((int)a - rot + (int)'Z') % (int)'Z';
        else if (a >= 'a' && a <= 'z')
            result += ((int)a - rot + (int)'z') % (int)'z';
        else
            result += a;
    }
    return result;
}

HZROT.h:

#include <string>
std::string ROTEncode(std::string instring, int rot);
std::string ROTDecode(std::string instring, int rot);

I use this code to encrypt/decrypt ROT, but it doesn't work correctly: Command line:

C:\Users\adm1n\Desktop\C\HZToolkit>hztoolkit --erot 13 abcdefghijklmnopqrstuvwyz

Outputs: nopqrstuvwxy So it doesn't work with letters after 'l'. Can you help me?

  • Hint: ASCII code of `A` is not 0, and that of `Z` is not 25. You need to do a little something before applying the mod `%` operator. – Igor Tandetnik May 06 '17 at 14:03
  • Thank you for answer. result += ((int)a-(int)'A' + rot) % 26 + 'A'; Should it be like this? It works, but looks a bit weird. – Zolboobayar G. May 06 '17 at 14:14
  • Well, it's either that, or not using `%` at all. Something like `int b = a + rot; if (b > 'Z') b -= 26; result += char(b);` – Igor Tandetnik May 06 '17 at 14:17

1 Answers1

0

Working code is:

#include "HZROT.h"

std::string ROTEncode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (IsBigLetter(a))
            result += ((int)a - (int)'A' + rot) % 26 + 'A';
        else if (IsSmallLetter(a))
            result += ((int)a - (int)'a' + rot) % 26 + 'a';
        else
            result += a;
    }
    return result;
}
std::string ROTDecode(std::string instring, int rot)
{
    std::string result;
    for (char a : instring)
    {
        if (IsBigLetter(a))
            result += ((int)a - (int)'A' - rot + 26) % 26 + 'A';
        else if (IsSmallLetter(a))
            result += ((int)a - (int)'a' - rot + 26) % 26 + 'a';
        else
            result += a;
    }
    return result;
}

And HZROT.h:

#include <string>

#define IsBigLetter(a) a >= 'A' && a <= 'Z'
#define IsSmallLetter(a) a >= 'a' && a <= 'z'

std::string ROTEncode(std::string instring, int rot);
std::string ROTDecode(std::string instring, int rot);