return(char)((((ch + key) - offset) % 26) + offset) 代码有什么作用?

What does return(char)((((ch + key) - offset) % 26) + offset) code do?

所以我在网上查找 C# 凯撒密码,我找到了这个网站: https://www.programmingalgorithms.com/algorithm/caesar-cipher

我仔细查看了代码,直到这一部分对我来说大体上是有意义的:

char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)((((ch + key) - offset) % 26) + offset);

三元运算符我懂了,主要是第二行看不懂,returns一个字符,但是不知怎么把一个字符和一个数相加,减去一个字符,得到模数然后加上一个字符?

我想出的唯一解释是每个角色都有一个 ID 并且它正在对它而不是角色本身进行操作? 老实说,这有点超出我的理解范围,如果有人能解释一下那就太好了。

提前致谢。

假设您按下了一个键,假设是 F,ASCII 码将为 0x46 因此:

int ch = 0x46;

然后值被 key 参数移动(让我们取 3)

int key = 21;

offset就是数值与ASCII码的偏移量:

'A' - 'A' = 0 -> A is at index 0 of letters
'B' - 'A' = 1 -> B is at index 1 of letters
...
'Z' - 'A' = 25 -> Z is at index 25

当字母为小写时,使用 'a'。

同样的事情

现在 % 26 对字母执行一些循环

因此 (('F' + 21) -'A') % 26 给出 0

然后回到字母范围: 0 + 'A' = 'A'

如您的标题所述,这只是 C 中的凯撒密码。

根据ECMA-334 (C# language spec)

The char type is used to represent Unicode code units. A variable of type char represents a single 16-bit Unicode code unit.

根据the unicode.org glossary*:

Code Unit. The minimal bit combination that can represent a unit of encoded text for processing or interchange. The Unicode Standard uses 8-bit code units in the UTF-8 encoding form, 16-bit code units in the UTF-16 encoding form, and 32-bit code units in the UTF-32 encoding form.

从这两个资源中我们可以推断出 char 类型是一个 16 位宽的二进制数字字段。有什么比 16 位整数更好的方法来实现 16 位宽的二进制数字字段,嗯?