Olá Galera, estou com um problemilha chato…
Eu quero saber como posso converter 1 numero longo para uma Array de Bytes;
E tambem depois conver o array de Bytes para Long…
Eu até consegui fazer, o problema é quando entram numeros negativos na historia.
Eu sei que numetos binarios negativos, tem que fazer "uma onda" ai pra representalos, mas n tenho a menor ideia de como fazer…
Peço que alguem me de uma LUZ nesse problema.
Ex:
public class NewClass {
public static void main(String[] args) {
// byte[] valRecebido = new byte[]{ // Valore recebido....;
// 68, 66, -43, -2
// };
long valorEnviado = -19578300L; // Valor enviado.
long valorEnviado2 = 19578300L; // Valor enviado.
System.out.println("Valor enviado em bytes:" + valorEnviado);
byte[] veBytes = longToBytes(valorEnviado);
for (int i = 0; i < veBytes.length; i++) {
System.out.print("" + veBytes[i] + ", ");
}
System.out.println("\n getLong = " + getLong(veBytes, 0, 4));
// Agora o Positivo
System.out.println("Valor enviado em bytes:" + valorEnviado2);
veBytes = longToBytes(valorEnviado2);
for (int i = 0; i < veBytes.length; i++) {
System.out.print("" + veBytes[i] + ", ");
}
System.out.println("\n getLong = " + getLong(veBytes, 0, 4));
}
public static byte[] longToBytes(long l) {
byte[] data = new byte[4];
for (int i = data.length - 1; i >= 0; i--) {
data[i] = (byte) (l & 0xFF);
l >>= 8;
}
return data;
}
public static long getLong(byte[] data, int offset, int length) {
long l = 0;
int i = 0;
while (i < length) {
l <<= 8;
l += data[offset + i] & 0xFF;
i++;
}
return l;
}
}