Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Way to compare subarray of bytes

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?

like image 966
pkran Avatar asked Mar 19 '23 11:03

pkran


2 Answers

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;
}
like image 82
Dmitry Ginzburg Avatar answered Mar 21 '23 23:03

Dmitry Ginzburg


It would be faster just to iterate, as copyOfRange reallocates memory and creates a new array.

public boolean isEqual(byte[] a1, byte[] a2, int size) {
    for(int i=0;i<size;i++)
        if (a1[i] != a2[i])
            return false;
    return true;
}
like image 42
Anubian Noob Avatar answered Mar 22 '23 01:03

Anubian Noob