XORs the bits in an arbitrary number of byte arrays. - Java java.lang

Java examples for java.lang:byte Array Bit Operation

Description

XORs the bits in an arbitrary number of byte arrays.

Demo Code


//package com.java2s;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] arrays = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(java.util.Arrays.toString(xor(arrays)));
    }// www  .j a  v a2s.c om

    /**
     * XORs the bits in an arbitrary number of byte arrays.
     *
     * @return The result of XORing the bits in the byte arrays.
     */
    public static byte[] xor(byte[]... arrays) {
        if (arrays.length == 0)
            return null;

        sortDecendingSize(arrays);

        byte[] result = new byte[arrays[0].length];

        for (byte[] array : arrays) {
            for (int i = 0; i < array.length; i++) {
                result[i] ^= array[i];
            }
        }

        return result;
    }

    public static void sortDecendingSize(byte[]... arrays) {
        Arrays.sort(arrays, new Comparator<byte[]>() {
            @Override
            public int compare(byte[] lhs, byte[] rhs) {
                if (lhs.length > rhs.length)
                    return -1;
                if (lhs.length < rhs.length)
                    return 1;
                else
                    return 0;
            }
        });
    }
}

Related Tutorials