Java - Write code to Compare two byte[] arrays, element by element, and returns the number of elements common to both arrays.

Requirements

Write code to Compare two byte[] arrays, element by element, and returns the number of elements common to both arrays.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        byte[] bytes1 = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int len1 = 42;
        byte[] bytes2 = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int len2 = 42;
        System.out.println(bytesDifference(bytes1, len1, bytes2, len2));
    }/*from   w w w  .  jav a  2s  .c  o m*/

    /**
     * Compares two byte[] arrays, element by element, and returns the
     * number of elements common to both arrays.
     *
     * @param bytes1 The first byte[] to compare
     * @param bytes2 The second byte[] to compare
     * @return The number of common elements.
     */
    public static final int bytesDifference(byte[] bytes1, int len1,
            byte[] bytes2, int len2) {
        int len = len1 < len2 ? len1 : len2;
        for (int i = 0; i < len; i++)
            if (bytes1[i] != bytes2[i])
                return i;
        return len;
    }
}

Related Exercise