Thread: Help with bit wise and bit shift operation

1. Member
Join Date
Feb 2011
Posts
2
Rep Power
0

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:
Java 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:
Java 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:
Java 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:
Java 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```
Last edited by tiagomac; 02-25-2011 at 04:45 PM.

2. -650001 doesn't fit in two bytes.

kind regards,

Jos

3. Member
Join Date
Feb 2011
Posts
2
Rep Power
0
Originally Posted by JosAH
-650001 doesn't fit in two bytes.

kind regards,

Jos
josAH, sorry, it's not 650001, it's 65000L (to make this a long object), i had to put a L (in caps) in the end to be more visible, sorry...

4. Originally Posted by tiagomac
josAH, sorry, it's not 650001, it's 65000L (to make this a long object), i had to put a L (in caps) in the end to be more visible, sorry...
I should buy me some glasses (or install another font). Your number to byte array method works fine. Vice versa you have to initialize your number to -1 (all bits set to 1) if the most important byte happens to be negative (also has its most important bit set to 1). Otherwise initialize your number to 0.

kind regards,

Jos

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•