C# - Reading a long from Java's DataOutputStream

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-19 15:33:01

问题


I'm using the DataOutputStream#WriteLong method in the java programming language to write a long to a stream, and I need to be able to read it from C# using the BinaryReader class from C# to try to read the data, the BinaryReader is connected to a NetworkStreamthat uses the TcpClient socket.

The java DataInputStream#ReadLong method is used to read the long value sent from the DataOutputStream in Java, however I'm trying to use the BinaryReader class to read this value.

Here's the method I have to read a long variable in C#

public static long ReadLong()
{
    return binaryReader.ReadInt64();
}

However this is causing inconsistency, For example, I sent two longs through Java:

-8328681194717166436 || -5321661121193135183

and when I read them on C# I received the following results:

 -7186504045004821876||-5642088012899080778

I can reproduce this as many times as I fun the application.


回答1:


As you can read in the java documentation, WriteLong writes output "high bytes first", this is also known as Big Endian. Meanwhile, .NET BinaryReader reads data as Little Endian. We need something that reverses the bytes:

public class BigEndianBinaryReader : BinaryReader
{
    private byte[] a16 = new byte[2];
    private byte[] a32 = new byte[4];
    private byte[] a64 = new byte[8];

    public BigEndianBinaryReader(Stream stream) : base(stream) { }

    public override int ReadInt32()
    {
        a32 = base.ReadBytes(4);
        Array.Reverse(a32);
        return BitConverter.ToInt32(a32, 0);
    }

    public Int16 ReadInt16BigEndian()
    {
        a16 = base.ReadBytes(2);
        Array.Reverse(a16);
        return BitConverter.ToInt16(a16, 0);
    }

    public Int64 ReadInt64BigEndian()
    {
        a64 = base.ReadBytes(8);
        Array.Reverse(a64);
        return BitConverter.ToInt64(a64, 0);
    }

    public UInt32 ReadUInt32BigEndian()
    {
        a32 = base.ReadBytes(4);
        Array.Reverse(a32);
        return BitConverter.ToUInt32(a32, 0);
    }
}


来源:https://stackoverflow.com/questions/27681542/c-sharp-reading-a-long-from-javas-dataoutputstream

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