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]
# 1
Why not post one of the non-working ideas? I'd guess that it can be fixed by judicious use of &0xff
YAT_Archivista at 2007-7-16 21:53:27 > top of Java-index,Other Topics,Algorithms...
# 2

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 > top of Java-index,Other Topics,Algorithms...
# 3
yep,for(int i =0; i < 4; i++){l <<= 8;l ^= (long)b[i] & 0xFF;}works, thanks!
rein8a at 2007-7-16 21:53:27 > top of Java-index,Other Topics,Algorithms...
# 4
but only for integers it seems. How is this possible?
rein8a at 2007-7-16 21:53:27 > top of Java-index,Other Topics,Algorithms...
# 5
In Javabyte is 8 bitsshort is 16 bitsinteger is 32 bitslong is 64 bits
tschodta at 2007-7-16 21:53:27 > top of Java-index,Other Topics,Algorithms...
# 6
Look at: http://forum.java.sun.com/thread.jspa?threadID=624574&messageID=3617384#3617384Gil
gilroittoa at 2007-7-16 21:53:27 > top of Java-index,Other Topics,Algorithms...
# 7

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!

RadcliffePikea at 2007-7-16 21:53:27 > top of Java-index,Other Topics,Algorithms...