Pessoal,
me tirem uma dúvida, estou com um 2 métodos que fazem o seguinte processo: 1 método converte um array de bytes para um Long e o outro converte de um Long para um array de bytes, até o momento o método tem funcionado Ok, no entanto apresentou um problema na hora da conversão quando for um número negativo, ou seja, ele só funciona bem quando é número positivo, já olhei, reolhei e não consigo achar a falha, se alguém poder ajudar, dando uma luz… segue os métodos:
byteArrayToLong:
/**
* Converts from byte array to long.
* @param b - byte array
* @param size - the length
* @return
*/
public static long byteArrayToLong(byte[] b, Integer size, boolean autoLength){
int length = 0;
if (autoLength){
length = b.length;
}else{
length = size;
}
long ourLong = 0;
for (int i = 0; i < length; i++){
ourLong |= b[i] & 0xFF;
if (i+1 < length) ourLong <<= 8;
}
return ourLong;
}
longToByteArray:
/**
* Converts long in byte array with the given size.
* @param l - the long value
* @param size - the size (length) to array.
* @return a byte[].
*/
public static byte[] longToByteArray(long l, int size){
byte[] bytes = new byte[size];
int p = 0;
for (int i = size-1; i >= 0; i--){
bytes[i] = (byte) ((l >> p) & 0x0ff);
p += 8;
}
return bytes;
}
Um exemplo de execução com número positivo e saída ok:
Long ourLong = 65000l;
byte[] inBytes = Utils.longToByteArray(ourLong, 2);
Long ourLongRecovered = Utils.byteArrayToLong(inBytes, null, true);
System.out.println("ourLong: "+ourLong+" ourLongRecovered: "+ourLongRecovered);
// ourLong: 65000 ourLongRecovered: 65000
Agora com número negativo que dá erro:
Long ourLong = -65000l;
byte[] inBytes = Utils.longToByteArray(ourLong, 2);
Long ourLongRecovered = Utils.byteArrayToLong(inBytes, null, true);
System.out.println("ourLong: "+ourLong+" ourLongRecovered: "+ourLongRecovered);
// ourLong: -65000 ourLongRecovered: 536