2017-05-06 71 views
1

HZROT.cpp:加密在C /解密ROT ++

#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

謝謝你的回答。 result + =((int)a-(int)'A'+ rot)%26 +'A'; 應該是這樣嗎?它有效,但看起來有點奇怪。 –

+0

嗯,不是,或者根本不使用'%'。像'int b = a + rot;如果(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);