If I have two byte[]
arrays, is there a built-in function to compare them ala C's memcmp()
?
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.
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.
The java.util.Arrays.equals(byte[], byte[]) method is your friend.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With