Como concatenar bytes para short ou int

0 respostas
java
J

Tive muitos problemas para achar uma solução para concatenar dois bytes em um short.
O método:

public static short junta(byte a,byte b){
    short s = 0;
    s = (a<<8) | b;
    return s;
}

Não funciona qundo vc tem um b que seja negativo pois o complemento em 1 do número negativo atrapalha.

Então resolvi fazer no modo hard.

public static short junta(byte left, byte right){
    short s = 0;
    s = (short)(left << 8);
    byte[] bs = new byte[16];
    for(int i = 0; i < 16; i++){
        if( ((short)(Math.pow(2,15-i)) & right) == (short)(Math.pow(2,15-i) ){
            bs[i] = 1;
        }else{
            bs[i] = 0;
        }
    }
    for(int i = 0; i < 8; i++){
        if( ((short)(Math.pow(2,15-i)) & s) == (short)(Math.pow(2,15-i) ){
            bs[i] = 1;
        }else{
            bs[i] = 0;
        }
    }
    short fim = 0;
    for(int i = 0; i < 16; i++){
        fim = (short) (fim + (Math.pow(2,15-i))*bs[i]);
    }
    return fim;
}

Este funcionou pra mim e pode facilmente ser adaptado para trabalhar com outros tipos primitivos.
Espero que ajude mais alguém.
Abç.

Criado 11 de fevereiro de 2016
Respostas 0
Participantes 1