Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda