Help with a simple encryption program?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • googleplexx
    New Member
    • Apr 2010
    • 3

    Help with a simple encryption program?

    Hello,

    I'm trying to make a simple Caesar cipher however instead of A-Z i want to also include 0-9. where 9 wraps back to A.

    The best i could can do shift letters and integers independently so a string like "TESTING SHIFT Z 9" with a key of 1
    becomes
    "UFTUJOH TIJGU A 0"

    9 wraps to 0 and Z wraps to A

    here is how I did that:

    Code:
        private char encryptChar(char c, int k) {
        	if (Character.isDigit(c))
        		return (char) ('0' + (c - '0' + k) % 10); //handles the ints
        	else if (Character.isLetter(c))
        		return (char) ('A' + (c - 'A' + k) % 26); //handles the letters
        	else
        		return c;
        }
    Is there a way I can make 9 wrap around to A such that instead of the traditional?

    so that instead of:
    ABCDEFGHIJKLMNO PQRSTUVXYZ (Z wraps to A)

    what i'm trying to do is:
    ABCDEFGHIJKLMNO PQRSTUVXYZ01234 65789 (9 wraps to A)

    Thanks in advance for any help!
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Change the mod to 36 for both, and adjust the final result accordingly. Here's how to work the digits:
    Code:
            char d;
            if (Character.isDigit(c)) {
                d = (char) ((c - '0' + k) % 36);
                if (d <= 9)
                  return '0' + d;
                else
                  return d - 10 + 'A';
             }
    You may need to cast where appropriate.

    Comment

    Working...