简体   繁体   中英

read byte array from C# that is written from Java

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);
}

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.

正如这篇帖子所指出的那样http://kirkwylie.blogspot.com/2008/11/c-binarywriter-is-little-endian-because.html C#BinaryWriter只支持小端,所以你必须在java网站上配置它订购方法http://download.oracle.com/javase/1.4.2/docs/api/java/nio/ByteBuffer.html#order%28java.nio.ByteOrder%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM