Caesar: A MATLAB function for encryption and decryption of strings.
Caesar
Encryption and Decryption of strings in MATLAB
Description
This MATLAB function named "caesar", I wrote for an assignment of an online course of Vanderbilt University via Coursera.
The function takes two inputs, namely feed and shift. and gives output as coded
feed: a string to be encrypted or an already encrypted string to be decrypted
Shift: a value to encrypt or decrypt the string
Remember that when we decrypt the string, we place an opposite sign before the shift ( if the shift is 45 then make it -45 or vice versa)
Algorithm
- Feed is converted to double ( data type)
- a copy of the feed is created
- divide the shift by 95 and take the remainder
- a for loop is created to the length of the feed
- if the sum of character and shift is greater than 126
- then the value above 126 is added to 31 and is saved as the new character in place of the original one.
- if the sum of character and shift is less than 32
- then character, shift, and 127 are added together and 32 is subtracted from the total
- and the result is saved as a new character in place of the original one.
- if the above two conditions are not matched, then character value and shift are simply added and stored as a new character in place of the original one.
- in the end, the created sample is converted to the char data type and is returned as the output of the function.
MATLAB Program
function coded=caesar(feed,shift)
%convert the feed into double
feed=double(feed);
%create a copy of feed
sample=feed;
%take the remainder of shift
shift=rem(shift,95);
%the conversion
for ii=1:length(feed)
if (feed(ii)+shift)>126
sample(ii)=31+rem(feed(ii)+shift,126);
elseif (feed(ii)+shift)<32
sample(ii)=127+(shift+(feed(ii)-32));
else
sample(ii)=feed(ii)+shift;
end
end
%Convert back in char data type
coded=char(sample);
end
Comments
Post a Comment