2008-09-23 60 views
7

System.IO.BinaryReader以little-endian格式讀取值。如何簡化BinaryReader的網絡字節順序轉換?

我有一個C#應用程序連接到服務器端的專有網絡庫。正如人們所期望的那樣,服務器端以網絡字節順序發送所有內容,但我發現在客戶端處理這個問題非常棘手,特別是對於無符號值。

UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32()); 

是我想出來的,以獲得正確的無符號數出流的唯一途徑,但是這似乎既尷尬又醜,而且我還沒有測試,如果這只是要剪掉高順序值,以便我必須玩轉BitConverter的東西。

有沒有一些方法我錯過了在整個事情中編寫一個包裝以避免在每次讀取時都會發生這些醜陋的轉換?看起來讀者應該有一個endian-ness選項來讓事情變得更簡單,但我沒有遇到任何問題。

+0

當字節可能表示一個本地整數時,原始代碼是否正常工作? – 2013-08-01 17:58:30

+0

現在它不會有幫助,但我爲BinaryReder/Writer創建了一個[連接故障單](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=484149)以支持Bigendian。去投票它[這裏](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=484149)。 – 2009-08-25 13:20:49

回答

5

沒有內置轉換器。這裏是我的包裝(如你所看到的,我只實現我所需要的功能,但結構是很容易改變自己的喜好):

/// <summary> 
/// Utilities for reading big-endian files 
/// </summary> 
public class BigEndianReader 
{ 
    public BigEndianReader(BinaryReader baseReader) 
    { 
     mBaseReader = baseReader; 
    } 

    public short ReadInt16() 
    { 
     return BitConverter.ToInt16(ReadBigEndianBytes(2), 0); 
    } 

    public ushort ReadUInt16() 
    { 
     return BitConverter.ToUInt16(ReadBigEndianBytes(2), 0); 
    } 

    public uint ReadUInt32() 
    { 
     return BitConverter.ToUInt32(ReadBigEndianBytes(4), 0); 
    } 

    public byte[] ReadBigEndianBytes(int count) 
    { 
     byte[] bytes = new byte[count]; 
     for (int i = count - 1; i >= 0; i--) 
      bytes[i] = mBaseReader.ReadByte(); 

     return bytes; 
    } 

    public byte[] ReadBytes(int count) 
    { 
     return mBaseReader.ReadBytes(count); 
    } 

    public void Close() 
    { 
     mBaseReader.Close(); 
    } 

    public Stream BaseStream 
    { 
     get { return mBaseReader.BaseStream; } 
    } 

    private BinaryReader mBaseReader; 
} 

基本上,ReadBigEndianBytes做繁重的工作,這是傳遞給BitConverter。如果您讀取大量字節,將會有一個確定的問題,因爲這會導致大量的內存分配。

1

我構建了一個自定義的BinaryReader來處理所有這些。它可作爲part of my Nextem library。它也有一個定義二元結構的非常簡單的方法,我認爲這對你有幫助 - 查看例子。

注意:它現在只在SVN中,但非常穩定。如果您有任何問題,請發送電子郵件至cody_dot_brocious_at_gmail_dot_com。

+0

謝謝。我有點希望避免選擇一個額外的庫依賴項,因爲這整個事情應該相當小和簡單,但我會記住。很高興看到許可證是明確的,但。 :) – 2008-09-23 21:37:03

相關問題