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 !

5
  • 1
    What have you got so far? Commented Jan 9, 2013 at 18:26
  • 3
    This should help you => stackoverflow.com/questions/726652/… Commented Jan 9, 2013 at 18:26
  • 1
    What have you tried? What are you having diffciulty with? It's not obvious what you need help with. I assume you don't want us to just write it for you. Commented Jan 9, 2013 at 18:26
  • 1
    A loop and for each element - pair make a xor. What is the problem? Commented Jan 9, 2013 at 18:28
  • I posted a solution, do you think it's good? Commented Jan 9, 2013 at 18:36

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

7 Comments

wow, what means b^array_2[i++]? b power array_2[1] ?
@user1843305 no. ^ is XOR operator in Java.
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?
@user1843305 read and learn about array indexes and post-increment please.
cast to byte required. see stackoverflow.com/questions/2003003/…
|
-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

1 Comment

There is no logicalXOR() method in Java.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.