Skip to content

Instantly share code, notes, and snippets.

@Ztuu
Last active October 11, 2023 08:18
Show Gist options
  • Save Ztuu/e9106e9095422a7d7266653f1e156366 to your computer and use it in GitHub Desktop.
Save Ztuu/e9106e9095422a7d7266653f1e156366 to your computer and use it in GitHub Desktop.
ROT13 Function in C
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet.
ROT13 is an example of the Caesar cipher.
This function takes a string and returns the string ciphered with Rot13.
If there are numbers or special characters included in the string, they are returned as they are.
Only letters from the latin/english alphabet are shifted, like in the original Rot13 "implementation".
*/
char *rot13(const char *src)
{
if(src == NULL){
return NULL;
}
char* result = malloc(strlen(src)+1);
if(result != NULL){
strcpy(result, src);
char* current_char = result;
while(*current_char != '\0'){
//Only increment alphabet characters
if((*current_char >= 97 && *current_char <= 122) || (*current_char >= 65 && *current_char <= 90)){
if(*current_char > 109 || (*current_char > 77 && *current_char < 91)){
//Characters that wrap around to the start of the alphabet
*current_char -= 13;
}else{
//Characters that can be safely incremented
*current_char += 13;
}
}
current_char++;
}
}
return result;
}
@denisdemaisbr
Copy link

thanks.

you need fix it. (strlen() + plus null terminator)

21 char* result = malloc(strlen(src))+1;
26 result[strlen(src)] = 0x0;

@Ztuu
Copy link
Author

Ztuu commented Oct 11, 2023

thanks.

you need fix it. (strlen() + plus null terminator)

21 char* result = malloc(strlen(src))+1; 26 result[strlen(src)] = 0x0;

Thanks for your input! I have updated the gist to now allocate 1 extra byte for the null character as strlen does not include this. However specifying the final character as the null character is not necessary as strcpy will include this when copying the original string. Thanks again 😀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment