views:

215

answers:

2

Hi!

Im am porting some stuff from C# to JAVA and I need a class that can convert bytes to primitives, just lite BitConverter in .NET can.

As I just posted here, I noted that my computer uses Little-Endian (Intel) and BitConverter works as expected:

// C# code
byte[] b2 = new byte[] { 0, 1 };
short b2short = BitConverter.ToInt16(b2, 0);

the b2short == 256 as expected.

Well, I needed a "BitConverter" in JAVA and found this piece of code. However, when I try it in JAVA it seems to me that the methods interpret the byte arrays as Big-Endian. JAVA-code:

// JAVA code
byte[] b2 = new byte[] { 0, 1 };
short b2short = MyFoundConverter.BitConverter.toShort(b2, 0);

In this case, b2short == 1 and that seems to me like Big-Endian.

The question: Can someone, that knows those bitwise operators, tell me if indeed the code found on this webpage is interpreting the byte array as Big-Endian?

If so, is there an easy way to make it Little-Endian?

Regards

A: 

The code you need is:

byte[] b2 = new byte[] { 0, 1 };
short b2short = b2[0] | (b2[1] << 8);

and for int values:

byte[] b4 = new byte[] { 0, 1, 2, 3 };
int b4int = b4[0] | (b4[1] << 8) | (b4[2] << 16) | (b4[3] << 24);

you get the idea :-)

rsp
+1  A: 

The code you linked to is taking the first byte, and making it the high-order byte of the short. The second byte goes into the low-order byte of the short. So this is a big-endian operation. The way it is coded, there would be no easy way to fix this, other than going method by method and swapping the array indexes, so that the highest index becomes the lowest.

I found another code bit that will take the data type and swap its endian-ness. Maybe you can combine the two.

jdmichal
Thx, I choose to do it manually by swapping the array indexes. ITs a few minutes work, and then moving on =)
Ted