开发者

Please verify: this converter reads the byte array as Big-Endian?

开发者 https://www.devze.com 2022-12-15 22:45 出处:网络
I am porting some stuff from C# to Java and I need a class that can convert bytes to primitives, just like BitConverter in .NET can.

I am porting some stuff from C# to Java and I need a class that can convert bytes to primitives, just like 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[]开发者_JAVA技巧 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.

Is the code found on this webpage interpreting the byte array as Big-Endian?

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


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.


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 :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消