简体   繁体   English

C#-从Java的DataOutputStream读取很长时间

[英]C# - Reading a long from Java's DataOutputStream

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 NetworkStream that uses the TcpClient socket. 我正在使用Java编程语言中的DataOutputStream#WriteLong方法向流写入long,我需要能够使用C#中的BinaryReader类从C#中读取它以尝试读取数据,BinaryReader已连接到使用TcpClient套接字的NetworkStream

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. Java DataInputStream#ReadLong方法用于读取Java中从DataOutputStream发送的long值,但是我试图使用BinaryReader类读取此值。

Here's the method I have to read a long variable in C# 这是我必须在C#中读取长变量的方法

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

However this is causing inconsistency, For example, I sent two longs through Java: 但是,这导致了不一致,例如,我通过Java发送了两个long:

-8328681194717166436 || -5321661121193135183

and when I read them on C# I received the following results: 当我在C#上阅读它们时,收到以下结果:

 -7186504045004821876||-5642088012899080778

I can reproduce this as many times as I fun the application. 我可以在对应用程序进行娱乐的过程中重现它多次。

As you can read in the java documentation, WriteLong writes output "high bytes first", this is also known as Big Endian . 如您在Java文档中所读, WriteLong将输出“先写高字节”,也称为Big Endian Meanwhile, .NET BinaryReader reads data as Little Endian. 同时,.NET BinaryReader将数据读取为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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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