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