Jorge Cabrera
Jorge Cabrera

Reputation: 341

Bitwise XOR operator and byte arrays

I have the following piece of code:

byte[] S = new byte[256];
byte[] T = new byte[256];

for (int i = 0; i < 256; ++i) {
    S[i] = (byte)i;
    T[i] = 13;
}

int j = 0;
int i2 = 0;
while (i2 < 256) {
    j = j + S[i2] + T[i2] & 255;
    byte[] arrby = S;
    int n2 = i2;
    arrby[n2] = (byte)(arrby[n2] ^ S[j]);
    byte[] arrby2 = S;
    int n3 = j;
    arrby2[n3] = (byte)(arrby2[n3] ^ S[i2]);
    byte[] arrby3 = S;
    int n4 = i2++;
    arrby3[n4] = (byte)(arrby3[n4] ^ S[j]);
}

The S[] array with the initial values: 0,1,2,3,4,5...

When the program reach the line:

arrby[n2] = (byte)(arrby[n2] ^ S[j]);

S[0] changes its value from '0' to '13' and I can't understand why. What is modifying the S[0] value? As I see it the '^' is just doing a comparison and changing the value of arrby[n2] but not of S[0]

Upvotes: 2

Views: 3400

Answers (2)

Adam  M.
Adam M.

Reputation: 1193

The line of code below makes arrby refference the same allocated memory as S

byte[] arrby = S;

Upvotes: 1

GhostCat
GhostCat

Reputation: 140427

Here:

byte[] arrby = S;

You are making arrby point to the same array as S.

Then:

arrby[n2] = (byte)(arrby[n2] ^ S[j]);

You are changing an entry in that array.

Tada ...

So, the solution is: if you don't want to modify the content of your array, make sure that you don't create other references pointing to that array. Depending on your requirements, you could for example copy the data from S into a freshly created arrby array first.

Upvotes: 6

Related Questions