Simple Encryption Code check
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Antworten (1)
Les Beckham
am 18 Dez. 2021
Bearbeitet: Les Beckham
am 18 Dez. 2021
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 Kommentare
Les Beckham
am 19 Dez. 2021
Bearbeitet: Les Beckham
am 19 Dez. 2021
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.
Siehe auch
Kategorien
Mehr zu Language Support finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!