Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
set byte if value cant fit

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!