C
C#2y ago
icy

Caesar shift

Hi, I'm making a C# program and part of it is based on a Caesar shift. I have searched examples of Caesar shifts online but I do not really understand how they work, for example some use modulus. I want to know how I can make it so if a character like Z is shifted forward by 1 letter it will loop back to A. Thank you! :D
6 Replies
MODiX
MODiX2y ago
TheRanger#3357
REPL Result: Success
public static char ShiftBy(char c, int i)
{
int index = c-'A';
index = (index + i) % 26;
return (char)('A' + index);
}
char c = 'Z';
Console.WriteLine(ShiftBy(c, 2));
public static char ShiftBy(char c, int i)
{
int index = c-'A';
index = (index + i) % 26;
return (char)('A' + index);
}
char c = 'Z';
Console.WriteLine(ShiftBy(c, 2));
Console Output
B
B
Compile: 589.674ms | Execution: 67.987ms | React with ❌ to remove this embed.
icy
icy2y ago
thank you, i'm not entirely sure how this code works though, what is the modulus for?
Klarth
Klarth2y ago
The modulus is for array wrapping. ie. You have an array of [A-Z] with indices [0-25]. So if you add one to Z, you get index 26 -> 0, which is A.
icy
icy2y ago
ohh, why does that work? I thought the modulus was for remainders is this a second use?
Tvde1
Tvde12y ago
this is the remainer 26 / 25 is 1 with a remainder of 1 if you would shift 'Z' by 105, you would get (25 + 105) % 25 = 5
icy
icy2y ago
ohhh i see thank you
Want results from more Discord servers?
Add your server
More Posts