Swap double problem

A

auc

I am attempting to swap big endian bytes to little endian format. Here
is a snippet of code which doesn't seem to work:

byte b[];

public double getDouble (int offset) {
long l = (b[offset+7] & 0xff) + ((b[offset+6] & 0xff) << 8) +
((b[offset+5] & 0xff) << 16) + ((b[offset+4] & 0xff) <<
24) +
((b[offset+3] & 0xff) << 32) + ((b[offset+2] & 0xff) <<
40) +
((b[offset+1] & 0xff) << 48) + (b[offset] << 56);
return Double.longBitsToDouble(l);
}

My class is initialized with an array of bytes and I use the offset to
position within the byte array. I have very similiar code to swap ints,
shorts and floats which works fine. What am I missing with doubles?

Thanks,
Gary V
 
C

Chris Uppal

((b[offset+1] & 0xff) << 48)

This expression (and the others like it) won't produce the results you expect.
The sub-expression

(b[offset+1] & 0xff)

is of type int, so the shift operator can only shift by at most 31 bits. In
fact (I'm sorry to say), the amount to shift by is /masked/ with 31, so the
shift expression is identical to:

(... << 16)

which is not what anyone would expect... To get the results you want, you
should ensure that the shiftee is of type long /before/ it is shifted. E.g
(untested).

(b[offset+1] & 0xffL) << 48

should do it.

-- chris
 
A

auc

Thanks for the helpful reply Chris. I tried your suggestion but didn't
get the proper conversion until I cast the byte as long as follows:

((long) b[offset+1] & 0xffL) << 48

You pointed me in the right direction - thanks.

Gary V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top