set byte if value cant fit

Viewed 55

I want to set a byte at max or min value, if the value I try to assign is greater. Is there a better way to do it, instead of checking with if statements?

example:

int[] arr = new int[128]; // assume int array is filled with random values
byte[] arr2 = new byte[128]; 

for (int i = 0; i < arr.length; i++) {
  if (arr[i] > 127) {
    arr2[i] = 127;
  } else if (arr[i] < -128) {
    arr2[i] = -128;
  } else {
    arr2[i] = arr[i];
  }
}

is there a way to replace the if/else statement with bitwise operations? Or is there a smarter/faster way to do that?

1 Answers

You could chain Math.min(int, int) and Math.max(int, int) calls. Like,

arr2[i] = (byte) Math.min(127, Math.max(-128, arr[i]));

If arr[i] is less than -128 that will take -128. If the result of that is greater than 127 it will take 127. Which should cover all of your cases.

Related