Skip to content

Instantly share code, notes, and snippets.

@khswong
Created January 15, 2020 05:56
Show Gist options
  • Save khswong/12febbfc59b8b8a3c477d73c101b33dd to your computer and use it in GitHub Desktop.
Save khswong/12febbfc59b8b8a3c477d73c101b33dd to your computer and use it in GitHub Desktop.
Quick Rot13 impl
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
const char upperAlpha[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char lowerAlpha[26] = "abcdefghijklmnopqrstuvwxyz";
int charPos(const char *alphabet, char letter) {
for (int i = 0; i < 26; ++i) {
if (letter == alphabet[i])
return i;
}
return -1;
}
void rot13(char *src, char *dst, size_t size) {
for (int i = 0; i < (int)size; ++i) {
if (charPos(upperAlpha, src[i]) != -1) {
int pos = charPos(upperAlpha, src[i]);
pos = (pos + 13) % 26;
dst[i] = upperAlpha[pos];
} else if (charPos(lowerAlpha, src[i]) != -1) {
int pos = charPos(lowerAlpha, src[i]);
pos = (pos + 13) % 26;
dst[i] = lowerAlpha[pos];
} else {
dst[i] = src[i];
}
}
}
int main() {
char *src = "Hello World!";
char *dst = malloc(strlen(src));
printf("%s \n", src);
rot13(src, dst, strlen(src));
printf("%s \n", dst);
rot13(dst, dst, strlen(dst));
printf("%s \n", dst);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment