![](/img/trans.png)
[英]Is it possible to send 0xFF in a byte array from Java to a USB device?
[英]Check if byte array are all in 0xff
是否有一种简单的方法可以在不循环的情况下检查java中的字节数是否全部为0xFF作为值?
例
byte[] b = new byte[]{ 0xff, 0xff, 0xff, 0xff, 0xff };
if (b is all 'ff')
process?
没有循环(显式或递归)的任何语言都无法做到这一点。 即使您的CPU有特殊指令来检查模式的存储区域,它也会在内部循环。 所以你的问题没有意义。
如果你想要一种有效的方法来做到这一点,有一些方法:
如果您的数组总是具有相同的长度,则可以设置常量并使用Arrays.equals()
。 如果你有几个不同的长度,但只有少数不同的长度,你可以创建几个常量。
您可以对数组进行排序并检查第一个和最后一个值。 如果它们相同,那么它们之间的所有值也必须为-1。
您可以将检查移动到方法中,这意味着“检查循环”不会使代码在重要位置混乱。
您可以使用JNI访问汇编代码,而汇编代码又使用特殊指令。
其他语言为这样的事情提供了更好的支持。 在Groovy中,你可以做b.size() == b.count { it == -1 }
如果你不喜欢循环,请使用递归:)
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));
}
疯狂的想法,你可以用字符串匹配来做到这一点
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.