Compare commits
2 Commits
main
...
c6b5f1bad7
Author | SHA1 | Date | |
---|---|---|---|
c6b5f1bad7 | |||
2f58a337f1 |
37
src/crypt.c
37
src/crypt.c
@@ -9,17 +9,50 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
#include "crypt.h"
|
#include "crypt.h"
|
||||||
|
#include <stdbool.h>
|
||||||
|
|
||||||
|
|
||||||
|
// Which of the two below functions is faster (find out!)
|
||||||
|
inline int mod(int a, int b)
|
||||||
|
{
|
||||||
|
return (a % b + b) % b;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
inline int fast_mod(int a, int b)
|
||||||
|
{
|
||||||
|
const int result = a % b;
|
||||||
|
return result >= 0 ? result : result + b;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
inline bool isupper(char c)
|
||||||
|
{
|
||||||
|
return c >= 'A' && c <= 'Z';
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void caesar_encrypt(char* str, int size, int key)
|
void caesar_encrypt(char* str, int size, int key)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < size && str[i] != '\n'; i++)
|
for (int i = 0; i < size && str[i] != '\n'; i++)
|
||||||
if (str[i] != ' ') str[i] += key % 26;
|
if (str[i] != ' ')
|
||||||
|
{
|
||||||
|
bool upper = isupper(str[i]);
|
||||||
|
str[i] += key - (upper ? 65 : 97);
|
||||||
|
str[i] %= 26;
|
||||||
|
str[i] += (upper ? 65 : 97);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void caesar_decrypt(char* str, int size, int key)
|
void caesar_decrypt(char* str, int size, int key)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < size && str[i] != '\n'; i++)
|
for (int i = 0; i < size && str[i] != '\n'; i++)
|
||||||
if (str[i] != ' ') str[i] -= key % 26;
|
if (str[i] != ' ')
|
||||||
|
{
|
||||||
|
bool upper = isupper(str[i]);
|
||||||
|
str[i] = str[i] - key - (upper ? 65 : 97);
|
||||||
|
str[i] = mod(str[i], 26);
|
||||||
|
str[i] += (upper ? 65 : 97);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user