8

I am working on Caesar Cipher and have written my code but do not know how to convert ascii to alphabetical index. This is what has got me stuck with this assignment for over a week. I have checked the video several times and do not see how it is done.

Anyone any suggestions?

7

@Tessa so if you want 'a' to equal 0 you could

char c = 'a';
printf ( "%i", (c - 97) );

Sometimes you kind of have to do things for yourself. There is a very good reason to represent a key character as "c minus some number" or (c - 97), as zero, a character is hard to distinguish as either 'a' and 'A'.

2
  • 1
    On the other hand, sometimes it's more clear if you use a char while doing the math (as mentioned in the class material). In this case, c - 'a' instead of c - 97 tells you that you are subtracting the ASCII value of lower case 'a' to get a number between 0 and 25, and not an uppercase 'A'.
    – Cliff B
    Aug 14 '15 at 1:23
  • Thank you! I think I was almost there as I was using the char function. Aug 14 '15 at 7:09
3

There is no "conversion" from ascii to alphabet. A char is simply a 1-byte integer that is interpreted using the ascii table. Run this little program to see what I mean:

#include <stdio.h>
int main(void)
{
    char letter = 'a';

    printf("letter in decimal: %d\n", letter);
    printf("letter as char: %c\n", letter);

    letter = letter + 10;

    printf("letter is now %c\n", letter);   
}

You should get:

letter in decimal: 97
letter as char: a
letter is now k

See how the char can be printed as either its character value 'a' or its decimal value 97? And you can do arithmetic on the letter in either form?

If you are trying to convert your a-z into the range of 0-25, remember that 'a' - 'a' equals zero. And 'z' - 'a' equals 25.

3
  • thank you, I understand. So in the calculation it still uses the ascii number of 97 doesn't it? I need the program to calculate a - z from 0 - 25 like the Alphabetical Index. So a = 0 and not 97 ;-) Aug 14 '15 at 0:18
  • Tessa, see my edit. Also, if I answered your question, please accept my answer so that this question will be marked a resolved.
    – curiouskiwi
    Aug 14 '15 at 1:25
  • Thank you curious kiwi :-) Aug 14 '15 at 7:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .