-
encryption algorithm
I am fairly new to coding in c. I am having trouble writing a function to read a character and encrypt the character so that
A becomes Z
B becomes Y
C becomes X
and so on.....
same with lowercase letters
Heres what i thought would work but i guess not. It only for capitals. I tried using ascii code but im pretty sure there is a simpler way to code this encryption process. thanks a lot.
Code:
char encryptAlpha (char strChar)
{
// Local Definitions
int i;
int j;
// Statements
if ((strChar > 64) && (strChar < 91))
{
for (i = 65, j = 90; i < 91, j > 64; i++, j--)
{
if (strChar == i)
strChar = j;
}
}
return strChar;
}// encryptAlpha
-
I'll need to look at it a bit more, but:
Don't use actual numeric values for letters in your code. It makes the whole thing unintelligable. Don't write:
Write:
It'll also make your code that much more portable should you happen across a weird platform where 'a' != 97.
_If_ I'm reading the code right, it looks like a simple substitution cipher where:
a = z
b = y
c = x
etc. ?
If so, don't use a for() look in the inside, it can be done with some if()s and a subtraction statement. (The function should be constant time)
-
Your expression, i < 91, j > 64 is equivalent to j > 64, because the comma operator returns only the value of the second expression. You'd probably be better off replacing the for loop with strChar = 'Z' - (strChar - 'A'); anyway, since that's a simpler way of achieving the same goal. Realize that the expression 'Z' is just just a cute way of writing the number 90, assuming you're using the ASCII character set. In fact, it'd be more readable to rewrite your 9th line with if ((strChar >= 'A') && (strChar <= 'Z')).
-
Got it figured out!! thanks for your guys input. Here is the code i finished with, Just another question. If you think it should receive any changes or could improve please say so. I am always up to helpful criticism and am always looking to improve my coding. thanks again.
Code:
char encryptAlpha (char strChar)
{
// Local Definitions
char firstChar;
char lastChar;
// Statements
if ((strChar >= 'A') && (strChar <= 'Z'))
{
firstChar = 'A';
lastChar = 'Z';
{
while ((firstChar <= 'M') && (lastChar >= 'N'))
{
if (strChar == firstChar)
strChar = lastChar;
else if (strChar == lastChar)
strChar = firstChar;
firstChar++;
lastChar--;
}
}
}
if ((strChar >= 'a') && (strChar <= 'z'))
{
firstChar = 'a';
lastChar = 'z';
{
while ((firstChar <= 'm') && (lastChar >= 'n'))
{
if (strChar == firstChar)
strChar = lastChar;
else if (strChar == lastChar)
strChar = firstChar;
firstChar++;
lastChar--;
}
}
}
return strChar;
}// encryptAlpha