long to byte array and back
I'm converting a long to a byte array for sending over a network like this:
long l = somevalue;
byte [] b =newbyte[4];
for(int i= 0; i < 4; i++){
b[3-i] = (byte)(l >>> (i * 8));
}
and then want to get my long back but I can't seem to get it to work. I've tried several options but none work. Any ideas?
[645 byte] By [
rein8a] at [2007-10-2 8:01:13]

My own solution is this:
for(int i =0; i < 4; i++){
l <<= 8;
l ^= (long)b[i];
}
But the result as binary string:
in as long: 1234567890
in as binary : 01001001100101100000001011010010
out as binary: 01001001011010011111110111010010
out as long: 1231683026
The bits are flipped in the b[1] and b[2] positions?
rein8a at 2007-7-16 21:53:27 >

import java.nio.*;
import java.nio.channels.*;
...
double val;
FooChannel channel = FooChannel.open();
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.putDouble(val);
channel.write(buf);
or even...
DoubleBuffer dblBuf = buf.asDoubleBuffer();
double[] vals = ...;
dblBuf.put(vals);
No bit twiddling required!