I'm working on a cryptography program that implements various traditional methods. For some of them it is best for my message to be represented as numbers 0-25. A is 0, B is 1, etc. This shift cipher is a case of that since you must take mod 26 for a wrap around. Also spaces and punctuation must be preserved. Here is the code for the method that does the shift cipher:
public static void shift(char k, char eord) { if(eord=='E' || eord=='e') { int [] mi= new int[mc.length]; for(int i=0; i<mc.length; i++) { if ((mc[i]>='a' && mc[i]<='z') || (mc[i]>='A' && mc[i]<='Z')) { mi[i]=(int)(mc[i]+k); mi[i]=mi[i]%26; //mc[i]=(char)mi[i]; //System.out.println(mi[i]); } } } } mc is an array of characters that holds the message and eord is a char that will determine whether to run the algorithm to encrypt or decrypt. What I have the code do is check to make sure that mc[i] is a letter and then add the char k (the key) and then I type cast it into an integer so I can mod 26. Something does not work correctly because when I have a key of 'b' (1) and see what the integer representation is it is definitely not correct. I also need to convert it back to a character when I'm done so I can give the user the plaintext/cipher text of the message.
51 Answer
To get an integer value of 0..25 of a character you need to make sure that you only get upper- or lowercase characters in the alphabet.
Let's assume lowercase. Then you can simply convert the characters to integer by subtracting the value of the 'a' character. As the character values are ordered as in the normal alphabet, this will give 'a' value of 0 and 'z' value of 25... and all the letters in between will get the correct value as well.
I'll show a lowercase version as I don't like shouting:
public class CharacterToZeroBasedIntegerRange { public static int characterToIntegerRange(char c) { if (c < 'a' || c > 'z') { throw new IllegalArgumentException(String.format("Character with value %04X is not a letter", (int) c)); } return c - 'a'; } public static void main(String[] args) { String test = "Hello world!".toLowerCase().replaceAll("[^a-z]", ""); System.out.println(test); for (int i = 0; i < test.length(); i++) { char c = test.charAt(i); System.out.println(characterToIntegerRange(c)); } } } 2