string conversion with number

Viewed 101

shift function should shift characters according to the number is given

   function shift_char(c: Character; n:Integer) return Character is
      I : Integer;
   begin
        if Is_Lower(c) then
            I:= ((((Character'Pos(c) rem 26) + n) mod 26) + 97);
        elsif Is_Upper(c) then
            I:= ((((Character'Pos(c) rem 26) + n) mod 26) + 65);
        end if;

      return Character'val(I);
   end;
1 Answers

As noted here, you first need to map the lowest character in each range to zero. Instead of rem 26, subtract the position of the initial character as shown in the variation below:

function Shift_Char (C : Character; N : Integer) return Character is
   Lower_A : constant Integer := Character'Pos (Lower'First);
   Upper_A : constant Integer := Character'Pos (Upper'First);
   I       : Integer          := Character'Pos (C);
begin
   if Is_Lower (C) then
      I := ((((I - Lower_A) + N) mod 26) + Lower_A);
   end if;
   if Is_Upper (C) then
      I := ((((I - Upper_A) + N) mod 26) + Upper_A);
   end if;
   return Character'Val (I);
end Shift_Char;

Console:

generated single_key is : 25
generated multi_keys list is : 16 8 25 11

before encryption with caesar: Ada Is Cool
encrypted:Zcz Hr Bnnk
decrypted: Ada Is Cool
before encryption with vigenere: Ada Is Cool
encrypted: Qlz Ti Knzb
decrypted: Ada Is Cool
Related