Java and C# - byte array to long conversion difference

China☆狼群 提交于 2019-12-22 04:53:08

问题


This is strange to me: when I run in Java

byte[] data = new byte[] { 50, -106, 40, -22, -94, -119, -52, 8 };
ByteBuffer bb = ByteBuffer.wrap( data );
System.out.println( bb.getLong() );

result is 3645145936617393160

when I run in C#

//unsigned values (signed&0xff)
byte[] bytes = new byte[] { 50, 150, 40, 234, 162, 137, 204, 8 };
long l = BitConverter.ToInt64(bytes, 0);
System.Console.Write(String.Format("{0}\n", l));
System.Console.ReadKey();

result is 634032980358633010

Can you help me to understand this?
Thanks!


回答1:


This is a difference in endianness.

If you reverse the byte array, it works as expected:

BitConverter.ToInt64(new byte[] { 8, 204, 137, 162, 234, 40, 150, 50 }, 0)

You can set the endianness in Java by calling bb.order(ByteOrder.LITTLE_ENDIAN).

By the way, the easiest way to play with these things is to use LINQPad.



来源:https://stackoverflow.com/questions/2289427/java-and-c-sharp-byte-array-to-long-conversion-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!