【发布时间】:2021-12-20 19:22:17
【问题描述】:
所以,我正在尝试按如下方式实现 XOR 加密:
string XOR(char *data, char *key) {
for (int i = 0; i != sizeof(data); i++)
{
data[i] ^= key[i % sizeof(*key)];
}
cout << sizeof(data) << "\n";
return data;
}
这是将data和key作为输入的函数
这里重要的是,对于数组data 中的每个字符,都使用键进行异或运算,因此for 循环:for (int i = 0; i != sizeof(data); i++)...
问题出现在 sizeof(data) 返回 4 或者我的预期输出将是 27 (字母表中的 26 个字母 + 空终止符(我认为))。
程序输出这个:
4
#"%efghijklmnopqrstuvwxyz
只有前 4 个字母被正确处理。
奇怪的是 sizeof(str) 返回 27 是正确的,那么为什么 sizeof(data) 返回 4 呢?
那么我需要在函数XOR的参数中更改什么?
这是完整的代码:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
string XOR(char *data, char *key) {
for (int i = 0; i < sizeof(data) + 1; i++)
{
data[i] ^= key[i % sizeof(*key)];
}
cout << sizeof(data);
return data;
}
int main()
{
char clef[] = "A";
char str[] = "abcdefghijklmnopqrstuvwxyz";
cout << XOR(str, clef) << "\n";
}
【问题讨论】:
-
另一个重复:Why is sizeof(str) is equal to 8 , when it should be equal to strlen(str)+1 ... (because of extra null char)?(当我在这个网站上搜索
[c++] sizeof strlen时第三次点击)