9

有没有一种简单的方法来检查java中的字节数组是否具有所有0xFF作为值?

例子

byte[] b = new byte[]{ 0xff, 0xff, 0xff, 0xff, 0xff };

if (b is all 'ff')
    process?
4

3 回答 3

4

没有循环(显式或递归)的任何语言都无法做到这一点。即使你的 CPU 有一个特殊的指令来检查内存区域的模式,它也会在内部循环。所以你的问题真的没有意义。

如果您要求一种有效的方法来做到这一点,有以下方法:

  • 如果您的数组始终具有相同的长度,您可以设置一个常量并使用Arrays.equals(). 如果您有几个不同的长度,但只有少量不同的长度,您可以创建多个常量。

  • 您可以对数组进行排序并检查第一个和最后一个值。如果它们相同,则它们之间的所有值也必须为 -1。

  • 您可以将检查移动到一个方法中,这意味着“检查循环”不会在重要位置混淆代码。

  • 您可以使用 JNI 访问汇编代码,而汇编代码又使用特殊指令。

  • 其他语言为此类事情提供更好的支持。在 Groovy 中,你可以做b.size() == b.count { it == -1 }

于 2012-05-14T08:30:07.293 回答
3

如果您不喜欢循环,请使用递归:)

 public static void test1() {
    class Chk {
        boolean c(int [] b, int val, int pos) {
            if (pos >= b.length) {
                return true;
            }
            if (b[pos] != val) {
                return false;
            }
            return c(b, val, pos + 1);
        }
    }
    Chk test = new Chk();

    System.out.println(test.c(new int [] {0xff, 0xff}, 0xff, 0));

    System.out.println(test.c(new int [] {0xff, 0xff, 0xff, 0xfe}, 0xff, 0));

    System.out.println(test.c(new int [] {0x01, 0x01, 0x01, 0x01}, 0xff, 0));

    System.out.println(test.c(new int [] {0x01, 0x01, 0x01, 0x01}, 0x01, 0));
}
于 2012-05-14T08:24:17.927 回答
1

疯狂的想法,你可以用字符串匹配来做到这一点

int[] b = new int[]{0xff, 0xff, 0xff, 0xff, 0xff};
String arr = Arrays.toString(b).replaceAll(", ", "");
String match = "\\[("+new Integer(0xff).toString()+")+\\]";
System.out.println(arr);
System.out.println(match);
System.out.print(arr.matches(match));
于 2012-05-14T09:00:30.417 回答