Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda