14

I have to apply an xor over two arrays like let's say I have :

array_1: 1 0 1 0 1 1
array_2: 1 0 0 1 0 1

I would like to have a function that accepts two arrays and returns an array applying the XOR, so in this case I would like this function to return:

returned_array: 0 0 1 1 1 0

Please help me with an algorithm .. Thanks !

Ben
  • 469
  • 2
  • 4
  • 20

2 Answers2

27

If you are storing these numbers in byte arrays, use this straightforward solution:

byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };

byte[] array_3 = new byte[6];

int i = 0;
for (byte b : array_1)
    array_3[i] = b ^ array_2[i++];

Output array:

0 0 1 1 1 0
Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • wow, what means b^array_2[i++]? b power array_2[1] ? – Ben Jan 09 '13 at 18:37
  • 1
    @user1843305 no. ^ is XOR operator in Java. – Juvanis Jan 09 '13 at 18:40
  • but the integer i doesn't increment does it? if it does that would mean that you do something like: b ^ array_2[1] and the i value becomes 1, so you're incrementing it and using it at the same time? – Ben Jan 09 '13 at 18:43
  • 2
    @user1843305 read and learn about array indexes and post-increment please. – Juvanis Jan 09 '13 at 18:46
  • `int i=5, j=5; int a = i++; int b = ++j; i and j value: 6. a value: 5 b value: 6. ` Don't know how comes I didn't know about this .. Thanks – Ben Jan 09 '13 at 18:49
  • I get this compile error: "possible loss of precision array_3[i] = b ^ array_2[i++]; required: byte found: int, 1 error" anyone knows why? – Karl Adler Jan 15 '14 at 20:38
  • cast to byte required. see http://stackoverflow.com/questions/2003003/why-does-the-xor-operator-on-two-bytes-produce-an-int – px5x2 May 03 '16 at 06:13
-3

Would this be a good solution? (I wrote this thanks to what you gave me)

if(array1.length==array2.length){
  for(int i=0;i<array1.length;i++){

    output.add(logicalXOR(array1.get(i),array2.get(i)))

  }
}

Of course array1,2 and output would be arrayLists

Ben
  • 469
  • 2
  • 4
  • 20