Check if all byte arrays are at 0xff

Is there an easy way to check without a loop, does the byte array in java have all 0xFF values?

Example

byte[] b = new byte[]{ 0xff, 0xff, 0xff, 0xff, 0xff }; if (b is all 'ff') process? 
+8
java arrays byte
source share
3 answers

If you don't like the loop, 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)); } 
+3
source share

There is no way to do this in any language without loops (explicit or recursive). Even if your processor has special instructions for checking the memory area for a template, it will loop inside. Therefore, your question does not make sense.

If you are asking for an effective way to do this, there are ways:

  • If your arrays always have the same length, you can adjust the 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 them must also be -1.

  • You can transfer validation to a method, which means that the “control loop” does not 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 such things. In Groovy you can do b.size() == b.count { it == -1 }

+4
source share

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)); 
+1
source share

All Articles