Trying to make a function for Caesar Encryption -- need help.
Afficher commentaires plus anciens
I've got a project which involves designing a GUI that can encrypt a string using Caesar encryption. I've been making this function file to use in the GUI .m file, but I've encountered some problems. I think I've got the method properly, I just can't seem to get it right without any errors.
function output = encCsar(word,key)
numWord = uint8(word);
numKey = uint8(lower(key)) - 96;
for i = 1:numel(numWord)
if ( numWord>=65 & numWord<=90 )
numWord=mod(numWord-65+numKey,26);
output(i,1)=char(numWord+65);
elseif ( numWord>=97 & numWord<=122 )
numWord=mod(numWord-97+numKey,26);
output(i,1)=char(numWord+97);
else
error('Please enter a string and a number key.')
end
end
My method is:
- Convert "word" (a string) into its respective numerical array in ASCII.
- Convert the key (one lowercase letter to determine how much to shift by) to its respective ASCII number.
- run a for loop that runs for each element of the numerical array numWord
- Apply the Caesar encryption formula (num value of the letter + num value of the key) in mod 26, and I had it run for both uppercase and lowercase letters just in case the string isn't completely lowercase or uppercase.
- It then outputs each encrypted element as a new array, and it converts it back to characters.
That's what it's supposed to do in theory, but I've gotten the error I set up ('Please enter a string and a number key.') in case it fails each time. If I try commenting out the else part, the function just doesn't do anything. How should I go about fixing this? Any answers or help would be appreciated.
Réponse acceptée
Plus de réponses (1)
Juan Sebastián Hincapié Montes
le 21 Août 2020
I've got a solution to this problems... hope this help you!
function [coded] = caesar(v ,sa)
secret = double(v);
code = ones(1, length(v));
for ii=1:length(secret)
if secret(ii)+sa > 126 %greater than 126
remainder=rem(sa,95);
if remainder + secret(ii)>126 %if the double plus the remainder is greater than 32
code(ii)=31+(remainder-(126-secret(ii)));
else
code(ii)=remainder+secret(ii); %if the double plus the remainder isn't greater than 32
end
elseif secret(ii)+sa < 32 %lower than 32
remainder=abs(rem(sa,95));
if secret(ii)-remainder < 32 %if the double plus the remainder is lower than 32
code(ii)=127-(remainder-(secret(ii)-32));
else
code(ii)=secret(ii)-remainder; %if the double plus the remainder isn't lower than 32
end
else
code(ii) = sa + secret(ii); %everything is normal
end
end
coded=char(code);
end
1 commentaire
MANIKANTA THOTA
le 15 Sep 2020
can you tell me why you took 95 in the reminder
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!