簡體   English   中英

與等效的Java代碼相比,C#BitConverter輸出錯誤的雙精度值

[英]C# BitConverter outputs wrong double value when compared to equivalent Java code

我正在嘗試將Java函數轉換為C#,但我無法弄清楚。 該函數應該將字節數組轉換為雙精度型。

假設這兩個函數應該做相同的事情,但事實並非如此。

我試過在C#中使用BitConverter,但這只會返回錯誤的double。

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#函數:(此返回錯誤的double)

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

對於Java中的字節數組= {64, -6, -51, 112, -93, -41, 10, 61} -41、10、61 {64, -6, -51, 112, -93, -41, 10, 61} ,我得到double = 109783.04(這是正確的轉換),而在C#中,我得到1.19203925203128E-14

您需要顛倒字節順序。 這與Little Endian和Big Endian之間的區別有關,后者是最低有效字節在前還是在后—您可以通過谷歌搜索了解更多信息。

Java將內容存儲在big endian中。 如果您的系統使用小尾數法,則在轉換之前需要反轉字節。 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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM