Simple Encryption Code check

8 次查看(过去 30 天)
Bil Ly
Bil Ly 2021-12-18
I have written a code to solve this problem:
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. Write a function called caesar that accepts two arguments: the first is the character vector to be encrypted, while the second is the shift amount. The function returns the output argument coded, the encrypted text. The function needs to work with all the visible ASCII characters from space to ~. The ASCII codes of these are 32 through 126. If the shifted code goes outside of this range, it should wrap around. For example, if we shift ~ by 1, the result should be space. If we shift space by -1, the result should be ~.
This is what I have so far, it almost works. When i put in "coded = caesar('ABCD', 3)" as the input, the output is "G" instead of "DEFG" and when the input goes outside the range, the output is just " ". Any help with what I am getting wrong would be appreciated
function [coded] = caesar(vector, shift)
i = double(vector);
x = i;
for j = 1:length(i);
if i(j) + shift > 126;
x = 126 + shift - 95;
elseif i(j) + shift < 32;
x = 32 + shift + 95;
else
x = i(j)+shift;
end
coded = char(x);
end

回答(1 个)

Les Beckham
Les Beckham 2021-12-18
编辑:Les Beckham 2021-12-18
You are only saving one element of x. You need to index x like you did i.
So:
function [coded] = caesar(vector, shift)
i = double(vector);
x = i;
for j = 1:length(i)
if i(j) + shift > 126
x(j) = 126 + shift - 95;
elseif i(j) + shift < 32
x(j) = 32 + shift + 95;
else
x(j) = i(j)+shift;
end
coded = char(x);
end
Result;
>> caesar('ABCD', 3)
ans =
'DEFG'
>>
  2 个评论
Bil Ly
Bil Ly 2021-12-18
Thanks, that makes sense. any idea why the function is outputting a blank space when i try to go above or below 32 or 126 on the table?
Les Beckham
Les Beckham 2021-12-19
编辑:Les Beckham 2021-12-19
32 is the ASCII code for a space. 127 is the ASCII code for DEL which is an "unprintable" character. Some of the ASCII codes correspond to actions that teletypes or other "old fashioned" devices were to take when they received those characters.
The typical printable English letters, numbers, and punctuation marks lie between 32 and 126. You can search "ASCII table" or look at the Wikipedia article on ASCII to learn more: ASCII
If this answered your question, please Accept the answer.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Language Support 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by