9

如果我有两个byte[]数组,是否有一个内置函数来比较它们 ala C 的memcmp()

4

6 回答 6

6

如果发现 s1 的前 n 个字节分别小于、匹配或大于 s2 的前 n 个字节,则 Memcmp 返回一个 int,小于、等于或大于零。Equals 返回一个布尔值。这不是同一个功能。此外,memcmp 将字节作为无符号字符进行比较。

我认为这可以工作:

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;
}

(编辑)事实上,2 的补码部分是不必要的:

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;
}
于 2013-09-07T20:26:12.340 回答
4

有 Arrays.equals()。

如果硬件中存在相应的指令,我不知道JVM实现是否真的对此进行了优化,但我对此表示怀疑。

另外,如果我没记错我的 C,strcmp 最多可以使用一个空终止符(使其对 C 字符串有用),数组版本将比较整个数组,因为 Java 程序员很少为空终止数组而烦恼。但是,如果您关心空终止符,您可以轻松编写自己的函数。

于 2009-07-07T02:31:46.523 回答
3

java.util.Arrays.equals(byte[], byte[])方法是你的朋友。

于 2009-07-07T02:47:47.077 回答
1

Well, Arrays.equals() is good, but cannot compare subranges. In this case there is also path through Arrays.listOf() and later .subList() but not for primitives like byte[].

Actually there is no direct memcmp() equivalent. Here is discussion and as soon as I know it is in the same state by now (15 years). Most 'native' implementation could be achieved by my option through java.nio.ByteBuffer (wrap() method and then equals()). But it is somewhat big amount of code.

For people which fully don't understand subject: memcmp() is implemented in platform dependent way which is very efficient and nothing in Java currently approaching it. Any manual cycles are far far away in term of performance at least because of index range checks. Maybe some day people who came from embedded C / C++ will be satisfied on this topic :-).

于 2013-05-20T13:16:39.127 回答
0

[数组.等于][1]

[1]: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#equals(byte[] , byte[])

于 2009-07-07T02:32:21.563 回答
0

在 Java 8 中,如果您可以将字节视为无符号值,这就是 C/C++ memcmp 实际所做的:

private static int memcmp(byte[] a, byte[] b, int sz) {
    for (int i = 0; i < sz; i++) {
        if (a[i] != b[i]) {
            return Byte.toUnsignedInt(a[i]) - Byte.toUnsignedInt(b[i]);
        }
    }
    return 0;
}
于 2019-01-08T19:40:45.247 回答