为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
繁星淼淼 2022-07-23 09:05:52
我正在尝试将 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
查看完整描述

1 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

您需要颠倒字节的顺序。这与 Little Endian 和 Big Endian 之间的区别有关,即最低有效字节是先出现还是最后出现 - 您可以通过谷歌搜索了解更多信息。


Java以大端存储东西。如果你的系统是小端的,你需要在转换之前反转字节。BitConverter 提供了一种确定字节序的方法。例如:


        // assuming we're starting with a big-endian byte[]

        // 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

        byte[] b = new byte[] { 64, 256-6, 256 - 51, 112, 256 - 93, 256 - 41, 10, 61 };

        bool little = BitConverter.IsLittleEndian;

        if (little)

        {

            byte[] nb = new byte[b.Length];

            for(int i =0; i<b.Length; i++)

            {

                nb[i] = b[b.Length - 1 - i];

            }

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

        }

        else

        {

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

        }


查看完整回答
反对 回复 2022-07-23
  • 1 回答
  • 0 关注
  • 278 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号