最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C语言中如何通过ASCII表实现简易加密操作
时间:2026-05-20 09:00:01 编辑:袖梨 来源:一聚教程网
通过C语言中的ASCII码特性,我们可以轻松实现基础的字符串加密功能。下面将详细介绍如何利用固定偏移量对字符进行加解密操作。

#include
#include
#define OFFSET 3
void encrypt(char *str) {
int i;
for(i = 0; i < strlen(str); i++) {
str[i] = str[i] + OFFSET;
}
}
void decrypt(char *str) {
int i;
for(i = 0; i < strlen(str); i++) {
str[i] = str[i] - OFFSET;
}
}
int main() {
char message[100];
printf("Enter a message to encrypt: ");
fgets(message, 100, stdin);
encrypt(message);
printf("Encrypted message: %sn", message);
decrypt(message);
printf("Decrypted message: %sn", message);
return 0;
}
上述代码演示了完整的加解密流程:
- 设定偏移量常量OFFSET为3
- encrypt函数将每个字符的ASCII码值增加3
- decrypt函数执行相反操作,将字符还原
- 主函数接收输入字符串后,依次调用加密解密函数
这种基于ASCII码的偏移加密虽然简单易懂,但仅适合教学演示,实际应用需要更强大的加密算法来确保信息安全。