Help with bit wise and bit shift operation
Friends,
I got two methods to make a conversion from byte array to long and the other to make from long to byte array, the problem is that when i use a number with a negative signal the code broken and the result is not the expected, so, if someone can give me a help i'll be thankful so much cause i tried everything but nothing worked
byteArrayToLong:
Code:
/**
* 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:
Code:
/**
* 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;
}
A running that gives a good result:
Code:
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
Now with a negative value that give the erro:
Code:
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