read byte array from C# that is written from Java

混江龙づ霸主 提交于 2021-02-07 12:38:21

问题


I am trying to write an Integer from C# and read it from Java. An integer is 4 bytes in both languages. However when I write it from C#, integer 1 is written in the following bytes 1000. Meaning the first byte is 1 and the rest is 0.

But in Java the same thing is written as 0001. Meaing the first 3 bytes are 0 and the last is 1.

Is there a simple way of reading and writing among these languages instead of manually reversing every 4 byte? The code for Java

ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(1);

for(byte b: buffer.array()){
      System.out.print(b);
}

The code for C#

MemoryStream ms = new MemoryStream();
using(BinaryWriter writer = new BinaryWriter(ms))
{
    writer.Write((int)1);

}
foreach(byte b in ms.ToArray()){
    Console.Write(b);
}

回答1:


As this post points aus http://kirkwylie.blogspot.com/2008/11/c-binarywriter-is-little-endian-because.html C# BinaryWriter supports only little endian so you have to configure it on the java site with the order method http://download.oracle.com/javase/1.4.2/docs/api/java/nio/ByteBuffer.html#order%28java.nio.ByteOrder%29




回答2:


You can switch the endianness on either of the sides to make them compatible.

For example on java side, you can set it to use ByteOrder.LITTLE_ENDIAN (default is BIG_ENDIAN )

In your case you can use ByteBuffer.order() to set the order.

buffer.order(ByteOrder.LITTLE_ENDIAN);

Or you can choose to change it on C# side in which case you'll have to make it Big-Endian to be compatible with java.



来源:https://stackoverflow.com/questions/5952062/read-byte-array-from-c-sharp-that-is-written-from-java

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