user1718720
user1718720

Reputation:

Java create a byte by XOR 2 bytes

I have 2 byte arrays, each containing 4 bytes (byte1[], byte2[]) and I want to XOR them to create a new 4 byte array (byte3[]) how would I do this?

(or even do each byte at a time then put them into the new array)

Upvotes: 7

Views: 26766

Answers (4)

Diego Basch
Diego Basch

Reputation: 13079

You can use the xor operation on bytes. It's the caret (^).

Example:

byte3[0] = (byte) (byte1[0] ^ byte2[0]);

Upvotes: 6

karim
karim

Reputation: 15589

This will work for equal or different size byte array as well.

   /** Return XOR of two byte array of different or same size. */
    public static byte[] xor(byte[] data1, byte[] data2) {
        // make data2 the largest...
        if (data1.length > data2.length) {
            byte[] tmp = data2;
            data2 = data1;
            data1 = tmp;
        }
        for (int i = 0; i < data1.length; i++) {
            data2[i] ^= data1[i];
        }
        return data2;
    }

Upvotes: 2

cyber-monk
cyber-monk

Reputation: 5560

You need to convert them to integers (no loss, primitive widening), do the XOR, then convert the resulting int back to a byte using a bit mask.

// convert to ints and xor
int one = (int)byte1[0];
int two = (int)byte2[0];
int xor = one ^ two;

// convert back to byte
byte b = (byte)(0xff & xor);

Example

String a        = "10101010";
String b        = "01010101";
String expected = "11111111";  // expected result of a ^ b

int aInt = Integer.parseInt(a, 2);
int bInt = Integer.parseInt(b, 2);
int xorInt = Integer.parseInt(expected, 2);

byte aByte = (byte)aInt;
byte bByte = (byte)bInt;
byte xorByte = (byte)xorInt;

// conversion routine compacted into single line
byte xor = (byte)(0xff & ((int)aByte) ^ ((int)bByte));


System.out.println(xorInt + "   // 11111111  as integer");
System.out.println(xorByte + "    // 11111111  as byte");

System.out.println(aInt + "   // a as integer");
System.out.println(bInt + "    // b as integer");
System.out.println((aInt ^ bInt) + "   // a ^ b as integers");

System.out.println(aByte + "   // a as byte");
System.out.println(bByte + "    // b as byte");

System.out.println(xor + "    // a ^ b as bytes");

Prints the following output

255   // 11111111  as integer
-1    // 11111111  as byte

170   // a as integer
85    // b as integer
255   // a ^ b as integers

-86   // a as byte
85    // b as byte
-1    // a ^ b as bytes

Upvotes: 13

Drakekin
Drakekin

Reputation: 1348

Java has a XOR operator in the form of ^. Just XOR each byte with each subsequent byte and put them in the new array.

Upvotes: 0

Related Questions