-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcipher.c
More file actions
51 lines (45 loc) · 1.17 KB
/
cipher.c
File metadata and controls
51 lines (45 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char *encrypt(char *string, short shift) {
size_t len = strlen(string);
unsigned short i;
char *new = NULL;
new = calloc(len + 1, sizeof(char));
for (i = 0; i < len; i++) {
char c = string[i];
int c_int = (int) c;
if (!isalpha(c_int)) {
new[i] = string[i];
continue;
}
if (isupper(c_int)) {
new[i] = (((c_int - 'A') + shift) % 26) + 'A';
if (new[i] < 'A') {
new[i] = 'Z' + 1 - ('A' - new[i]);
}
} else {
new[i] = (((c_int - 'a') + shift) % 26) + 'a';
if (new[i] < 'a') {
new[i] = 'z' + 1 - ('a' - new[i]);
}
}
}
return new;
}
char *decrypt(char *string, short shift) {
return encrypt(string, -shift);
}
void print_shift(short shift) {
printf("Alphabet:\t");
unsigned char i;
for (i = 'a'; i <= 'z'; i++) {
printf("%c ", i);
}
printf("\nShifted:\t");
for (i = 0; i < 26; i++) {
printf("%c ", ((i + shift) % 26) + 'a');
}
printf("\n");
}