Caesar's cypher is the simplest encryption algorithm. It adds a fixed value to the ASCII (unicode) value of each character of a text. In other words, it shifts the characters. Decrypting a text is simply shifting it back by the same amount, that is, it substract the same value from the characters.
我的任务是编写一个函数:
- 接受两个参数:第一个是要加密的字符向量,第二个是移位量。
- 返回一个输出,即加密文本。
- 需要处理从空格到
~
(ASCII 代码 32 到 126)的所有可见 ASCII 字符。如果移位后的代码超出此范围,它应该回绕。例如,如果我们将~
移动1
,结果应该是空格。如果我们将空格移动-1
,结果应该是~
。
这是我的 MATLAB 代码:
function [coded] = caesar(input_text, shift)
x = double(input_text); %converts char symbols to double format
for ii = 1:length(x) %go through each element
if (x(ii) + shift > 126) & (mod(x(ii) + shift, 127) < 32)
x(ii) = mod(x(ii) + shift, 127) + 32; %if the symbol + shift > 126, I make it 32
elseif (x(ii) + shift > 126) & (mod(x(ii) + shift, 127) >= 32)
x(ii) = mod(x(ii) + shift, 127);
elseif (x(ii) + shift < 32) & (126 + (x(ii) + shift - 32 + 1) >= 32)
x(ii) = 126 + (x(ii) + shift - 32 + 1);
elseif (x(ii) + shift < 32) & (126 + (x(ii) + shift - 32 + 1) < 32)
x(ii) = abs(x(ii) - 32 + shift - 32);
else x(ii) = x(ii) + shift;
end
end
coded = char(x); % converts double format back to char
end
我似乎无法正确进行换行转换(例如,从 31 到 126、30 到 125、127 到 32,等等)。我应该如何更改我的代码才能做到这一点?
最佳答案
甚至在开始编写此类代码之前,您应该牢牢掌握如何解决问题。
您遇到的主要障碍是如何将模运算应用于数据,查看 mod
如何将输入“包装”到 [0 modPeriod-1]
的范围内,而您自己的数据在 [32 126]
范围内。为了使 mod
在这种情况下有用,我们执行一个中间步骤,将输入移动到 mod
“喜欢”的范围,即从一些[minVal maxVal]
到 [0 modPeriod-1]
。
所以我们需要找到两个东西:所需类次的大小,以及mod
的周期大小。第一个很简单,因为这只是 -minVal
,它是第一个字符的 ASCII 值的负数,即空格(在 MATLAB 中写为 ' '
).至于 mod
的周期,这只是您的“字母表”的大小,恰好是“移位后比最大值大 1”,或者换句话说 - 最大值-最小值+1
。本质上,我们正在做的是以下内容
input -> shift to 0-based ("mod") domain -> apply mod() -> shift back -> output
现在看看如何使用 MATLAB 的矢量化符号来编写它:
function [coded] = caesar(input_text, shift)
FIRST_PRINTABLE = ' ';
LAST_PRINTABLE = '~';
N_PRINTABLE_CHARS = LAST_PRINTABLE - FIRST_PRINTABLE + 1;
coded = char(mod(input_text - FIRST_PRINTABLE + shift, N_PRINTABLE_CHARS) + FIRST_PRINTABLE);
这里有一些测试:
>> caesar('blabla', 1)
ans =
'cmbcmb'
>> caesar('cmbcmb', -1)
ans =
'blabla'
>> caesar('blabla', 1000)
ans =
'5?45?4'
>> caesar('5?45?4', -1000)
ans =
'blabla'
关于algorithm - 凯撒密码加密算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55217777/