Search code examples
ccs50caesar-cipher

how can i convert my alphabetical index back to Ascii code in C?


string plaintext = get_string("plaintext;");
  
  for (size_t k = 0; k<strlen(plaintext); k++)
  {
    int n = atoi(argv[1]);
    int m = plaintext[k] -'a' + 1;
    printf("%d", (m + n) % 26);
  }

in this piece of code i'm trying to cipher text that is inputted by the user. this: (m + n) % 26 ( m is i'th char of plaintext & n is key) is the formula i'm supposed to use.

i tried printing this:

printf("%d", (m + n) % 26);

as a char, but it won't print out. when i tried printing it out as an int as shown above, it outputted a number that is not in Ascii value (for ex.: 1294). i figured out that converting my index back to Ascii value would solve the problem, but i don't know how to do that.

  • please elaborate in your answer!

Solution

  • If this is a generic ROTN type thing then converting back is easy:

    printf("%c", (m + n) % 26 + 'a' - 1);
    

    Where you just have to "undo" what you did earlier.