与等效的 Java 代码相比,C# BitConverter 输出错误的双精度值

我正在尝试将 Java 函数转换为 C#,但我无法弄清楚。该函数应该将字节数组转换为双精度。


假设这两个函数应该做同样的事情,但他们没有。


我曾尝试在 C# 中使用 BitConverter,但这只会返回错误的双精度。


static double readBytes(RandomAccessFile in){ 


    byte a, b, c, d, e, f, g, h; 


    a = in.readByte(); 

    b = in.readByte(); 

    c = in.readByte(); 

    d = in.readByte(); 

    e = in.readByte();

    f = in.readByte();

    g = in.readByte();

    h = in.readByte();

    byte[] ba = { h, g, f, e, d, c, b, a }; 


    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(ba)); 

    double x = dis.readDouble(); 


    return x; 

转换后的 C# 函数:(这个返回错误的双精度)


protected internal static double readBytes(FileStream @in)

{

    byte a, b, c, d, e, f, g, h;

    a = (byte)@in.ReadByte();

    b = (byte)@in.ReadByte();

    c = (byte)@in.ReadByte();

    d = (byte)@in.ReadByte();

    e = (byte)@in.ReadByte();

    f = (byte)@in.ReadByte();

    g = (byte)@in.ReadByte();

    h = (byte)@in.ReadByte();

    byte[] ba = { h, g, f, e, d, c, b, a };

    double doub = BitConverter.ToDouble(ba, 0);

    return doub;

}

对于字节数组 ={64, -6, -51, 112, -93, -41, 10, 61}在 Java 中我得到 double = 109783.04 (这是正确的转换),在 C# 中我得到 1.19203925203128E-14


繁星淼淼
浏览 280回答 1
1回答

神不在的星期二

您需要颠倒字节的顺序。这与 Little Endian 和 Big Endian 之间的区别有关,即最低有效字节是先出现还是最后出现 - 您可以通过谷歌搜索了解更多信息。Java以大端存储东西。如果你的系统是小端的,你需要在转换之前反转字节。BitConverter 提供了一种确定字节序的方法。例如:&nbsp; &nbsp; &nbsp; &nbsp; // assuming we're starting with a big-endian byte[]&nbsp; &nbsp; &nbsp; &nbsp; // we check if we're using little endian, and if so convert the byte[] to little endian (by reversing its order) before doing the double conversion&nbsp; &nbsp; &nbsp; &nbsp; byte[] b = new byte[] { 64, 256-6, 256 - 51, 112, 256 - 93, 256 - 41, 10, 61 };&nbsp; &nbsp; &nbsp; &nbsp; bool little = BitConverter.IsLittleEndian;&nbsp; &nbsp; &nbsp; &nbsp; if (little)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; byte[] nb = new byte[b.Length];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int i =0; i<b.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nb[i] = b[b.Length - 1 - i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; double doub = BitConverter.ToDouble(nb, 0);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; double doub = BitConverter.ToDouble(b, 0);&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP