Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent of memcmp() in Java?

If I have two byte[] arrays, is there a built-in function to compare them ala C's memcmp() ?

like image 228
Jason S Avatar asked Jul 07 '09 02:07

Jason S


People also ask

What is Memcmp stands for?

In the C Programming Language, the memcmp function returns a negative, zero, or positive integer depending on whether the first n characters of the object pointed to by s1 are less than, equal to, or greater than the first n characters of the object pointed to by s2.

What is Memcmp CPP?

std::memcmp() in C++It compares the first count characters of the arrays pointed to by buf1 and buf2. Syntax: int memcmp(const void *buf1, const void *buf2, size_t count); Return Value: it returns an integer. Parameters: buf1 : Pointer to block of memory.


2 Answers

The java.util.Arrays.equals(byte[], byte[]) method is your friend.

like image 92
lavinio Avatar answered Oct 13 '22 12:10

lavinio


Memcmp returns an int, less than, equal to, or greater than zero if the first n bytes of s1 is found, respectively, to be less than, to match, or be greater than the first n bytes of s2. Equals returns a boolean. It's not the same function. In addition, memcmp compares bytes as unsigned chars.

I think this could work:

public int memcmp(byte b1[], byte b2[], int sz){
    for(int i = 0; i < sz; i++){
        if(b1[i] != b2[i]){
            if(b1[i] >= 0 && b2[i] >= 0)
                return b1[i] - b2[i];
            if(b1[i] < 0 && b2[i] >= 0)
                return 1;
            if(b2[i] < 0 && b1[i] >= 0)
                return -1;
            if(b1[i] < 0 && b2[i] < 0){
                byte x1 = (byte) (256 + b1[i]);
                byte x2 = (byte) (256 + b2[i]);
                return x1 - x2;
            }
        }
    }
    return 0;
}

(edit) In fact, the 2's complement part is not necessary:

public static int memcmp(byte b1[], byte b2[], int sz){
    for(int i = 0; i < sz; i++){
        if(b1[i] != b2[i]){
            if((b1[i] >= 0 && b2[i] >= 0)||(b1[i] < 0 && b2[i] < 0))
                return b1[i] - b2[i];
            if(b1[i] < 0 && b2[i] >= 0)
                return 1;
            if(b2[i] < 0 && b1[i] >=0)
                return -1;
        }
    }
    return 0;
}
like image 45
esoriano Avatar answered Oct 13 '22 13:10

esoriano