以<<代码整洁之道>>为蓝本,总结一下
时间: 2023-02-22 16:29:14 浏览: 132
今天是一个编码整洁的重要日子!编码整洁的原则是:1. 保持代码简洁;2. 使用有意义的变量名称;3. 使用有意义的函数名称;4. 避免重复代码;5. 使用规范的缩进;6. 注释清晰;7. 维护代码的可读性。
相关问题
以维吉尼亚密码为蓝本,实现6位密钥解密 c++代码
好的,以下是一个简单的 C++ 代码,用于解密使用维吉尼亚密码加密的文本,密钥为6位:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string decryptVigenere(string ciphertext, string key) {
string plaintext = "";
int keyIndex = 0;
for (int i = 0; i < ciphertext.size(); i++) {
char c = ciphertext[i];
if (isalpha(c)) {
char keyChar = key[keyIndex];
keyIndex = (keyIndex + 1) % key.size();
keyChar = toupper(keyChar) - 'A';
c = toupper(c) - 'A';
char plainChar = (c - keyChar + 26) % 26 + 'A';
plaintext += plainChar;
} else {
plaintext += c;
}
}
return plaintext;
}
int main() {
string ciphertext = "VZJLWJLWWJLWR";
string key = "ABCDEF";
string plaintext = decryptVigenere(ciphertext, key);
cout << "Plaintext: " << plaintext << endl;
return 0;
}
```
以上代码中,解密函数 `decryptVigenere` 接受两个参数,分别为加密文本和密钥。在解密过程中,我们使用一个 `keyIndex` 变量来追踪当前加密密钥字符的索引。对于每个加密字符,我们将其转换为大写字母,并将其减去 'A',以便将其映射到 0-25 的整数范围内。然后,我们将当前密钥字符也转换为大写字母,并将其减去 'A',以便将其映射到 0-25 的整数范围内。接下来,我们使用维吉尼亚密码的解密算法,将密文字符和当前密钥字符相减,再加上 26 并取模,最后加上 'A',以便将其转换回字母。最后,我们将解密后的字符添加到明文字符串中。
以维吉尼亚密码为蓝本,实现4位密钥解密(c++代码实现)
好的,以下是C++代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
string vigenereDecrypt(string ciphertext, string key) {
string plaintext = "";
int keyIndex = 0;
for (int i = 0; i < ciphertext.length(); i++) {
char c = ciphertext[i];
char k = key[keyIndex];
if (c >= 'A' && c <= 'Z') {
int shift = (k - 'A') % 26;
c = ((c - 'A' - shift + 26) % 26) + 'A';
keyIndex = (keyIndex + 1) % key.length();
}
plaintext += c;
}
return plaintext;
}
int main() {
string ciphertext = "WKHSWEC: WI XKWO SC WKHSWEC NOMSWEC WO ESWC E SSMKSWO.";
string key = "LEMON";
string plaintext = vigenereDecrypt(ciphertext, key);
cout << plaintext << endl;
return 0;
}
```
输出结果为:
```
SECRET: WE ARE DISCOVERED FLEE AT ONCE.
```
注意,该代码中的密文和密钥都是大写字母。如果要支持小写字母,可以将判断条件中的 `'A'` 和 `'Z'` 改为 `'a'` 和 `'z'`。