Fast Way to compare subarray of bytes

arrays, byte, compare, java, mask

Solution

You may write your helper method, it would be faster, than allocation of a new copy:

public boolean equalsInRange (byte[] arr1, int from1, int to1, byte[] arr2, int from2, int to2) {
    if (to1 - from1 < 0 || to1 - from1 != to2 - from2)
        return false;
    int i1 = from1, i2 = from2;
    while (i1 <= to1) {
        if (arr1[i1] != arr2[i2])
            return false;
        ++i1;
        ++i2;
    }
    return true;
}

Problem

In the scope of a project that I'm currently working, I use binary data stored in arrays of 10 bytes, and I'm trying to find a fast way to compare them. I'm mostly interested in the 5 most significant bytes, so I want to perform a comparison between sub-arrays of bytes. For instance, I have these two parameters: ``` byte [] indicator = new byte[5]; byte [] current = new byte[10]; ``` I want to see of the 5 first bytes of the 'current' is equal to the 'indicator'. In order to do so, I'm using the Arrays functions, so I'm actually doing the following: ``` Arrays.equals(indicator, Arrays.copyOfRange(current, 0, 5)) ``` This works fine of course, but not so fast as required. So I strongly believe that there must be a better way to perform such a byte comparison. Maybe by using `0xFF` masks??? Any ideas?

Original source