Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange wrong char's encryption (ascii)

It's a simple code but I can't understand a strange event. Code:

void Crittografia::CifraTesto(char text[]){
    int i;
    for (i=0;i<strlen(text);i++){
        text[i]=text[i] + key;
        if(text[i] > 'z'){
            text[i]=text[i] - 26;
        }
    }
}

The function receives the string entered here: It works.
In this case it works with a key of 5. 'y' changed in 'd' correctly.

But in this case: Doesn't work.
With a key of 7 it changes 'y' in 'Ç' instead of the correct 'f', so apparently doesn't execute the row: "text[i]=text[i] - 26;"

like image 747
Marco Rossi Avatar asked Feb 08 '23 08:02

Marco Rossi


1 Answers

text[i]=text[i] + key;

When key is 7 and text[i] is 'y' addition result doesn't fit in char (seems your char is signed) and result is implementation defined.

You are better of using a modulo operator in the addition. e.g.

text[i]= (text[i] - 'a' + key) % 26 + 'a';
like image 107
Giorgi Moniava Avatar answered Feb 16 '23 03:02

Giorgi Moniava