2017-05-06 41 views
1

HZROT.cppでROTを解読:暗号化/ C++

#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); 

私はROTを暗号化/復号化するために、このコードを使用しますが、それは正しく動作しません。 コマンドライン:

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

出力:nopqrstuvwxy だからでは動作しません。 'l'の後の文字。手伝って頂けますか?コード作業

+0

ヒント:A' 'のASCIIコードが0ではない、と' Z'のそれはあなたが必要25ではありませんmod '% '演算子を適用する前に少し何かをすることです。 –

+0

ありがとうございました。 結果+ =((int)a-(int) 'A' +腐敗)%26 + 'A'; それはこのようなものでしょうか?それは動作しますが、少し奇妙に見えます。 –

+0

さて、それはどちらか、あるいは '%'をまったく使っていないかのどちらかです。 'int b = a + rotのようなもの; if(b> 'Z')b - = 26;結果+ = char(b); ' –

答えて

0

は次のとおりです。

#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; 
} 

そして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);