views:

277

answers:

4

This may seem a stupid question but I can't find the anwer...

This is the code for XXTEA from Wikipedia:

#include <stdint.h>
#define DELTA 0x9e3779b9
#define MX ((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z));

void btea(uint32_t *v, int n, uint32_t const k[4]) {
  uint32_t y, z, sum;
  unsigned p, rounds, e;
  if (n > 1) {          /* Coding Part */
    rounds = 6 + 52/n;
    sum = 0;
    z = v[n-1];
    do {
      sum += DELTA;
      e = (sum >> 2) & 3;
      for (p=0; p<n-1; p++)
        y = v[p+1], z = v[p] += MX;
      y = v[0];
      z = v[n-1] += MX;
    } while (--rounds);
  } else if (n < -1) {  /* Decoding Part */
    n = -n;
    rounds = 6 + 52/n;
    sum = rounds*DELTA;
    y = v[0];
    do {
      e = (sum >> 2) & 3;
      for (p=n-1; p>0; p--)
        z = v[p-1], y = v[p] -= MX;
      z = v[n-1];
      y = v[0] -= MX;
    } while ((sum -= DELTA) != 0);
  }
}

I am porting this to C#. I don't know what I am overlooking, but where is the result of the encryption stored? I assume it is in v, but data from v is never set, only read.

What is it that I don't see?

+2  A: 

In the coding part: z = v[n-1] += MX;

In the decoding part: y = v[p] -= MX;

Those lines are executing += on an element of the v array and then copying the new value into z or y. Whomever wrote the code was prioritizing brevity over clarity, which is generally not a good thing in practical use.

Alan
Thanks very much. How could I not have seen that...
Ruud v A
+1  A: 

Operators = -= += has the same priority in expressions and they are associated from right to left according to C++ Standard 5.17 (and I believe there is the same rule in C) . For example, this:

y = v[p] -= MX;

Could be replaced with:

v[p] -= MX; // <<< modification of data here
y = v[p];
Kirill V. Lyadvinsky
+1  A: 

v is set in this line for example:

y = v[0] -= MX;

That could also be written as:

v[0] = v[0] - MX;
y = v[0];
Georg Fritzsche
+1  A: 

The data in the array at the end of pointer v is updated, though:

v[p] += MX;
...
z = v[n-1] += MX;
...
z = v[p-1], y = v[p] -= MX;
...
y = v[0] -= MX;

So yes; it is the data referred to be v that is updated.

Marc Gravell