Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if byte array are all in 0xff

Tags:

java

arrays

byte

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?
like image 965
jantox Avatar asked May 14 '12 08:05

jantox


2 Answers

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));
}
like image 39
DRCB Avatar answered Nov 09 '22 12:11

DRCB


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 }

like image 53
Aaron Digulla Avatar answered Nov 09 '22 11:11

Aaron Digulla