Reputation: 2185
Is there a simple way to check without looping whether a byte array in java has all 0xFF as values?
example
byte[] b = new byte[]{ 0xff, 0xff, 0xff, 0xff, 0xff };
if (b is all 'ff')
process?
Upvotes: 9
Views: 5360
Reputation: 8926
crazy idea, you can do it with string matching
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));
Upvotes: 1
Reputation: 328760
There is no way to do that in any language without loops (either explicit or recursive). Even if your CPU has a special instruction to check a memory area for a pattern, it will loop internally. So your question doesn't really make sense.
If you're asking for an efficient way to do this, there are ways:
If your arrays always have the same length, you can setup a constant and use Arrays.equals()
. If you have several different lengths but only a small number of different ones, you can create several constants.
You can sort the array and check the first and last value. If they are the same, then all values between must be -1, too.
You can move the check into a method, which means the "check loop" doesn't clutter the code in an important place.
You can use JNI to access assembler code which in turn uses special instructions.
Other languages offer better support for things like this. In Groovy, you can do b.size() == b.count { it == -1 }
Upvotes: 4
Reputation: 2121
If you don't like looping, use recursion :)
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));
}
Upvotes: 3