2013-01-18 186 views
9

我使用下面的代碼來使用BinaryReader來讀BigEndian信息,但我不確定它是否是有效的方法。有沒有更好的解決方案?高效的讀取C#中的大端數據的方法

這裏是我的代碼:

// some code to initialize the stream value 
// set the length value to the Int32 size 
BinaryReader reader =new BinaryReader(stream); 
byte[] bytes = reader.ReadBytes(length); 
Array.Reverse(bytes); 
int result = System.BitConverter.ToInt32(temp, 0); 

回答

12

BitConverter.ToInt32首先不是很快。我只是使用

public static int ToInt32BigEndian(byte[] buf, int i) 
{ 
    return (buf[i]<<24) | (buf[i+1]<<16) | (buf[i+2]<<8) | buf[i+3]; 
} 

你也可以考慮一次讀取超過4個字節。

+0

謝謝這是非常有趣的,但要確保我正確地得到了這個想法,你能解釋我們如何可以讀取超過4個字節。 –

+1

只需調用較大長度的'ReadBytes',然後使用不同的'i'來讀取數組中不同位置的整數。但這是一個你應該在基準測試之後才能進行的優化。 – CodesInChaos

+0

非常好。謝謝 –

相關問題