Problem with an equation

Im using this code to encrypt a text
1
2
3
4
5
6
void encrypt (char a[] ) 
{
    
for( int i=0; a[i] != '\0'; ++i ) ++a[i] = a[i] + 3 * 4 / 5 * 23 - 12;

}


and this to decrypt
1
2
3
4
5
6
void decrypt (char a[] ) 
{
  
for( int i=0; a[i] != '\0'; --i ) --a[i] = a[i] + 12 / 23 * 5 / 4 - 3  ;

}


but the decryption dosent work as wanted :/ any tips on what the problem is?
Last edited on
Hi nilsson,

In the decrypt function after 1st iteration i gets decremented to -1, which will be creating problem for a[i].

Also keep a close look in to the Precedence of C++ Operator .....
Last edited on
I agree with DiprenduDas ---- that bit of math(s) is very suspicious
Formatting pls, this isn't the obfuscated C contest.

Your encryption code looks fine, but your decryption is a little off as you have said. Remember, to Decrypt you need to do the exact opposite of what you have done to encrypt. This can be as simple as changing 1 operator and your target for the assignment.

e.g.
1
2
3
4
5
6
7
8
9
10
11
void encrypt (char a[] ) {
  for( int i=0; a[i] != '\0'; ++i ) {
    ++a[i] = a[i] + ((((3 * 4) / 5) * 23) - 12);
  }
}

void decrypt (char a[] ) {
  for( int i=0; a[i] != '\0'; ++i ) {
    --a[i] = a[i] - ((((12) / 5) * 23) - 12) ;
  }
}

Topic archived. No new replies allowed.