Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XOR over two arrays [closed]

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 !

like image 512
Ben Avatar asked Jan 09 '13 18:01

Ben


People also ask

How do you find the XOR of two arrays?

Therefore, the following steps are followed to compute the answer: Create a variable to store the XOR of the array as a result. For each element in the array, find the XOR of the element and the result variable using '^' operator. Finally, the result variable stores the XOR of all elements in the array.

How does XOR work in Java?

Bitwise XOR (exclusive or) "^" is an operator in Java that provides the answer '1' if both of the bits in its operands are different, if both of the bits are same then the XOR operator gives the result '0'. XOR is a binary operator that is evaluated from left to right.

How do you find the maximum XOR of an array?

For a given number N, the maximum possible XOR value is 2^log2(N) + 1.


1 Answers

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
like image 193
Juvanis Avatar answered Oct 06 '22 09:10

Juvanis