NotInCheck
NotInCheck

Reputation: 21

How is the fastest way to check each digit of a byte array in Java?

Given an arbitrary byteArray I need to check if a digit is greater than 9, if so the method returns false. I came to this solution, but I think it's a better way of doind that (maybe with some unary operations or other tricks):

for (int i : byteArray)
    if (i/16 > 0x09 || i%16 > 0x09) return false;

I tried to convert the number to a string, but it was slower.

Upvotes: 0

Views: 225

Answers (1)

office.aizaz
office.aizaz

Reputation: 303

How about this?

byte[] arr = new byte[] {0x00, 0x01, 0x02};
for (byte b : arr) {
      if (b > 0x09) {
          return false;
      }
}

As mentioned in comment, OP is interested in comparing each 'nibble':

byte[] arr = new byte[] {0x00, 0x01, 0x02};
for (byte b : arr) {
      if ((b & 0xF0) > 0x90 || (b & 0x0F) > 0x09) {
          return false;
      }
  }

Upvotes: 1

Related Questions